- Back to Home »
- C plus »
- Defining a Class In structure
Posted by : UTariq
Tuesday, September 24, 2013
We simply can define a class in a structure and also structure in class. When we define a class in a structure, then class become a member of the structure. And we can access a class in main function by using ''dot(.)'' operator.
A very simple example is here from which you can easily understand.
Example:
In this example i define a structure and in the structure i also define a class with its public and private data member. As i know that in class we can't directly access the private data member, that's why i declare a function through which we can access the private data member of the class. In this example I mentioned both of the methods to access a private data member and public data member in a structure.
#include<iostream>
#include<conio.h>
using namespace std;
struct A
{
class
test
{
private:
int
number;
public:
int
number1;
int
function(int);
};
test num; // class object
int a;
};
int A::test::function(int p)
{
number=p;
return
number;
}
int main()
{
A str;
int
node;
node=str.num.function(22); // For accessing the private data member of the class
cout<<node;
str.num.number1=13; // // For accessing the public data member of the class
cout<<str.num.number1;
getch();
}