Reputation: 4440
I've got the following classes:
class A {
void commonFunction() = 0;
}
class Aa: public A {
//Some stuff...
}
class Ab: public A {
//Some stuff...
}
Depending on user input I want to create an object of either Aa or Ab. My imidiate thought was this:
A object;
if (/*Test*/) {
Aa object;
} else {
Ab object;
}
But the compiler gives me:
error: cannot declare variable ‘object’ to be of abstract type ‘A’
because the following virtual functions are pure within ‘A’:
//The functions...
Is there a good way to solve this?
Upvotes: 1
Views: 540
Reputation: 596713
'A' is an abstract class. It has no implementation of its own for commonFunction(), and thus cannot be instantiated directly. Only its descendants can be instantiated (assuming they implement all of the abstract methods).
If you want to instantiate a descendant class based on input, and then use that object in common code, do something like this instead:
A* object;
if (/*Test*/) {
object = new Aa;
} else {
object = new Ab;
}
...
object->commonFunction();
...
delete object;
Upvotes: 2
Reputation: 84189
As others noted, runtime polymorphism in C++ works either through pointer or through reference. In general you are looking for Factory Design Pattern.
Upvotes: 2
Reputation: 12656
Use a pointer:
A *object;
if (/*Test*/) {
object = new Aa();
} else {
object = new Ab();
}
Upvotes: 7
Reputation: 1869
A * object = NULL;
if (/*Test*/) {
object = new Aa;
} else {
object = new Ab;
}
Upvotes: 2