Paul
Paul

Reputation: 4440

Create object of unknown class (two inherited classes)

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

Answers (4)

Remy Lebeau
Remy Lebeau

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

Nikolai Fetissov
Nikolai Fetissov

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

Cory Petosky
Cory Petosky

Reputation: 12656

Use a pointer:

A *object;
if (/*Test*/) {
    object = new Aa();
} else {
    object = new Ab();
}

Upvotes: 7

Ray
Ray

Reputation: 1869

A * object = NULL;
if (/*Test*/) {
    object = new Aa;
} else {
    object = new Ab;
}

Upvotes: 2

Related Questions