top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

In C, Can a structure have member function, access specifier?

+1 vote
484 views

I have written a simple program and stored it with .c file,
When i compiled it with g++ it is getting compiled and giving the proper output when i run that,
but when i compile the same using gcc then it is throwing error.

Below is the sample .c file
#include<stdio.h>
struct A{
        private:
        int a;
        public:
        int sum(){
        a=10;
        }
        void print()
        {
        printf("%d\n",a);
        }
        A()
        {
                printf("Constructor\n");
        }
        A(int b)
        {
                printf("Copy Constructor\n");
        }
        ~A()
        {
                printf("Destructor\n");
        }
};
main()
{
        struct A a(10);
        a.sum();
        a.print();
}
posted May 3, 2016 by Chirag Gangdev

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

In C++ there is no difference between structure and class except members of a class are private by default and members of struct are public by default.

In C you can not define a function within a struct, though you can have a function pointer in a struct.

answer May 3, 2016 by Salil Agrawal
So, i think even though file name is .c or .cpp,
if we compile it through g++ then it consider it as cpp only, correct?
Similar Questions
+7 votes
#include<stdio.h>

int &fun()
{
   static int x;
   return x;
}   

int main()
{
   fun() = 10;
   printf(" %d ", fun());

   return 0;
}

It is fine with c++ compiler while giving error with c compiler.

+4 votes
printf ("%s %d %f\n", (*ptr+i).a, (*ptr+i).b, (*ptr+i).c);
[Error] invalid operands to binary + (have 'struct name' and 'int')

where ptr is a pointer to the structure and allocated dynamic memory using malloc. Any suggestion would be helpful.

Thanks in advance.

+4 votes

Can someone explain me the usage of function pointer? Probably with real time examples ?

+5 votes

Even I have similar problem:

int (*pfun)(void);
int *pInt = 0;
void fun1()
{
    int i = 5; /* Local to fun1*/

    printf("Outer function");
    pInt = &i; /* As I know address of local variable is valid till function execution */

    int fun2()
    {
      printf("innerfunction");
      printf("%d", *pInt);
    }
    /* fun2 address assign to pfun so that It can be called even after completion of fun1 */
    pfun = fun2;
}

int main()
{
    fun1();
    pfun();
    return 0;
}

Can someone please explain ? I am getting *pInt value 5.

...