Hi,
Can we use structures within classes as data type? if yes then please give some examples?
Thanks
Hi,
Can we use structures within classes as data type? if yes then please give some examples?
Thanks
Building on , and , here are practical patterns and gotchas when embedding a struct inside a class that go beyond the simple example already posted.
Keep the nested type where it belongs. If external code must name the type, put the struct in the public section or expose an alias. If the type is an implementation detail, keep it private. Large nested definitions can be forward-declared inside the class and defined out of line to keep headers tidy:
class Outer {
public:
struct Inner; // forward declaration
Inner* make();
};
struct Outer::Inner { // out-of-class definition
int value;
}; For cleaner client code, provide a public alias (C++11+):
class Rect {
public:
struct Point { int x, y; };
using PointType = Point;
Rect(PointType a, PointType b);
private:
Point ul, lr;
};
Rect::PointType p{0,0}; A few cautions: nested types are members but do not magically gain privileged access to the other class instance data — use explicit friend declarations if needed. If the nested struct manages resources, obey the Rule of Three/Five. Prefer a top-level type when the type will be reused across components to avoid tight coupling. For language details (scoping, access, out-of-class definition) see the C++ reference on nested classes: cppreference - nested classes.
Jump to Post— vmanes 1,165Yes, 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; …
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.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.