Hi,
Can we use structures within classes as data type? if yes then please give some examples?

Thanks

Recommended Answers

All 2 Replies

Yes, when you might want to aggregate multiple data members.
This is rather trivial example, but illustrates how it might be done.

#include <iostream>
using namespace std;

class foo 
{
public:
	foo( );
	void display( );

private:
	struct pt
	{
		int x;
		int y;
	};
	pt point;

};

foo::foo( )
{ 
	point.x = 0;
	point.y = 0;
}

void foo::display( )
{
	cout << "(" << point.x << "," << point.y << ")";
}

int main( )
{
	foo a;

	a.display( );
	cout << endl;

	return 0;
}

You might have multiple point members in the class - say an upper left and lower right points to describe a rectangle.

You can do the same with classes. In C++ a struct is a class. The only difference is that a struct's data members are public by default... while a class's are private by default.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.