开发者

Create object of unknown class (two inherited classes)

I've got the following classes:

class A {
    void commonFunction() = 0;
}

class Aa: public A {
    //Some st开发者_JAVA百科uff...
}

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?


Use a pointer:

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


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


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


'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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜