Friday, May 20, 2016

Structure in C vs Structure in C++ :: Can we define function in structure

Structure in C vs Structure in C++ :: Can we define function structure

There are few major difference between structure in C and C++. While I was studying I always remains confused if structure can have function or not, if yes then whether in C or in C++.
Because I have studied that structure can not have function as member function. But in internet in many places I have seen function inside structure by searching many websites I found yes structure can also have member function but only in C++ not in C.
I have written a short program to understand it.

The important difference between class and structure is that by default in class member remains in Private while in structure it remain in public.

In C we can not define function inside structure but we can use pointer to function here.

In C++
We can do all things as we do in Class in C++ except the members of structure always remain public.
We can define function,constructor,destuctor in Structure also in C++.

See the below code of structure written in C++ for better understanding. It explains how we can define function,constructor and de-structure in structure in C++.

#include<iostream>
#include<cstring>
using namespace std;
struct student
{
    int roll_no;
    char *name;
    student()
    {
        roll_no=0;
        name = new char[100];
        }
    student(int rn,const char* name1)
    {
        roll_no=rn;
        name = new char[strlen(name1)+1];
        strcpy(name,name1);
    }
    void getData()
    {cout<<"Enter Roll number::";
        cin>>roll_no;
        cout<<"\nEnter name::";
        cin.ignore();
        cin.getline(name,100);
    }
    void display()
    {
        cout<<"\nRoll Number::"<<roll_no;
        cout<<"\nName::"<<name;
    }
    ~student()
    {
        cout<<"\nDestructor called for"<<this;
    }
};
int main( )
{
    student s1;
    s1.getData();
    s1.display();
    student s2;
    s2=s1;
    s2.display();
    student s3(226,"Mukesh Kumar");
    s3.display();
    return 1;
}












Please share your views and knowledge. Please comment below for any more information and also if you find any thing wrong in this post.

No comments:

Post a Comment