views:

68

answers:

4

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?

+2  A: 
A * object = NULL;
if (/*Test*/) {
    object = new Aa;
} else {
    object = new Ab;
}
Ray
+7  A: 

Use a pointer:

A *object;
if (/*Test*/) {
    object = new Aa();
} else {
    object = new Ab();
}
Cory Petosky
Works like a charm. Thanks!
Paul
+2  A: 

As others noted, runtime polymorphism in C++ works either through pointer or through reference. In general you are looking for Factory Design Pattern.

Nikolai N Fetissov
+2  A: 

'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;
Remy Lebeau - TeamB