top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Can I define/declare functions within a structure in C++?

+2 votes
260 views

Is it possible like

struct Point
{
int X;
int Y;
void Display() { cout << " string"; }
};
posted Oct 21, 2014 by Amit Kumar Pandey

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

2 Answers

+1 vote
 
Best answer

Yeah it is possible in C++ but it is not possible in C.
If you want to use in C then use a function pointer.

For C++ here is an working code:

#include <iostream>
using namespace std;

struct Point
{
   int X;
   int Y;
   void Display() { cout << "Hello World!\n"; }
};

int main()
{
    struct Point p;
    p.Display();

    return 0;
}
answer Oct 21, 2014 by Arshad Khan
+1 vote

You can always define functions in a structure in C++ but not in C. The only difference between class and structure is the scope of variable which is by default private for class and public for the structure and for all other practical purpose both are same.

answer Oct 21, 2014 by Salil Agrawal
Similar Questions
+1 vote

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();
}
...