Reputation: 2210
Say that we have a base A class and a derived B class:
struct A
{
A(int a) : a(a) {}
int a;
};
struct B : public A
{
B(int a, int b) : A(a), b(b) {}
int b;
};
Is there any way to define the B class without knowing the A class' constructor? For instance a factory class may be responsible for providing the data that the A class needs but the writter of the B class doesn't have to know anything about it. Basically assuming that we don't delegate the constructors is it possible to first initialize the A class part of an object and then initialize the B part using another set of constructor arguments?
Upvotes: 1
Views: 119
Reputation: 507
You can't inherit from incomplete type. If you just forward declare the base class you will get a compile-time error. For example, in gcc
(I have 4.8.1) you will get a invalid use of incomplete type
error. So, you can't hide class declaration if that class is going to be the base class.
Upvotes: 0
Reputation: 31519
You could use a variadic templated constructor that can forward its arguments to the base class [1]
struct B : public A
{
template<typename...Ts>
B(int b, Ts&&...args) : A(std::forward<Ts>(args)...), b(b)
{
}
int b;
};
But the above would not be any of any practical use unless [2] the base class was itself a generic aspect, eg
template<typename Base>
struct B : public Base
{
template<typename...Ts>
B(int b, Ts&&...args) : Base(std::forward<Ts>(args)...), b(b)
{
// above the initialization of b (its related argument)
// are not part of the variadic pack
}
int b;
};
1. The above would imply that a related factory method also uses variadic templates
2. Considering just a class that wants to construct its base without knowing how many or what type of variables it's constructed from. Uses may vary depending on context
Upvotes: 2
Reputation: 582
A derived class needs to see the full definition of it's base class, so no, you can't define B without A's definition (which involves it's constructors).
You need to check, if you really need inheritance here. If you don't, then A and B can be separate classes (so B isn't a derived class of A), and you can construct them separately. Then e.g. you can create a third class which has members of A and B.
Upvotes: 0