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++.

using namespace std;
struct student
    int roll_no;
    char *name;
        name = new char[100];
    student(int rn,const char* name1)
        name = new char[strlen(name1)+1];
    void getData()
    {cout<<"Enter Roll number::";
        cout<<"\nEnter name::";
    void display()
        cout<<"\nRoll Number::"<<roll_no;
        cout<<"\nDestructor called for"<<this;
int main( )
    student s1;
    student s2;
    student s3(226,"Mukesh Kumar");
    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