Lets say you have the class a
and you want to add a child class b
how would you go by doing this? Maybe something like this:
class a{
public:
class b{
};
};
Maybe it did make the class but as its clasified as an obj how would you make one. Like if you were to implement a as an object in your code it would look something like this:
a myObj;
But what about implementing b from a?
CodePudding user response:
Yes it can
Lets take the following example:
/// define the outer struct
struct Outer{
/// Define the inner struct
struct Inner {};
/// Up to this point, Outer has NOTHING in it, only a definition for
/// Inner without any objects.
/// And now inside Outer you can use Inner struct for anything you want.
/// For example Outer can have (but not required) a member called data of
/// type Inner like:
Inner data;
};
/// Now we create an object of type Outer:
Outer a;
/// Now a has a member called data of type Outer::Inner
/// Note in global scope Inner is undefined, you don't have Inner,
/// only Outer::Inner!!
/// But if Inner is public (i have used struct so it is) you can create
/// Outer::Inner objects:
Outer::Inner b;
/// Now b is an object of type Outer::Inner
CodePudding user response:
TL;DR: inside class a
: b obj
. outside the class a::b obj
I think you don't quite understand what instantiation and implementation mean.
When you IMPLEMENT (or rather, in this case, EXTEND) a class, you create a SUBCLASS.
When you INSTANTIATE a class (call its ctor or new
), you create an INSTANCE, an OBJECT.
So, if your question is whether you can extend an inner class, the answer is yes, of course you can: classes are, at their core, just namespaces. So, you can create another class in the namespace a
that extends the class a::b
.
Example:
class a {
public:
class b {
virtual void printsomething() { printf("This is the original\n"); }
};
class c: b {
virtual void printsomething() override { printf("This is the new\n"); }
}
};
If your question was whether you can instantiate an inner class, then the answer is still yes. As before, classes are just namespaces. So you can do something like this:
class a {
class b {
void printsomething() { printf("PRINTING...\n"); }
};
void dosomething() {
b obj;
obj.printsomething();
}
};
In either case, you can also instantiate the inner classes from outside class a
like so:
int main() {
a::b obj1;
obj1.printsomething();
a::c obj2;
obj2.printsomething();
}