简体   繁体   中英

Polymorphism on a static data member of a C++ class

Can polymorphism be used on a static data member of a C++ class (aka "class variable")?

Update: As b4hand stated, polymorphic methods must be declared in the base class. But that won't be possible in this scenario because it is not known in advance what methods the user will create in containerDerived.

I edited the example to include references; thank you for reminding me.

Here is my attempt to initialize a static base type (numBase) to a derived type (numDer):

#include <iostream>

class numBase                   //numBase is in a library user can not edit
{
};

class numDer : public numBase   //user defined class is a kind of numBase
{
    private:
        int num;
    public:
        void printNum() { std::cout << " numDer=" << num; }
        void inc() { num++; }
};

class containerBase             //containerBase is in a library user can not edit
{
    protected:
        //static numDer& count; //this compiles, but count can not be initialized to other types
        static numBase& count;  //this causes error six lines down from here
};

class containerDerived : public containerBase //user defined class is a kind of containerBase
{
    public:
        void inc() { count.inc(); } //error: 'count' was not declared in this scope
        void printCount() { std::cout << " containerDerived"; count.printNum(); }
};

/************************ user program **********************/
//initilialize static variable
numDer number;              //number could be any user defined type derived from numBase
numDer& containerBase::count = number; //initialize count to a kind of numBase

int main()
{
    containerDerived container1;
    containerDerived container2;

    container1.printCount();
    container1.inc();
    container2.inc();
    container1.printCount();
}

Thank you.

static numBase count;   

You have declared count to be an object of numBase. And through that object you are trying to call member of derived class of numBase ie numDer.inc(). This call surely won't succeed as run time polymorphism is only suitable when pointers/references are used.

You can't do what you're trying to do in the way you are trying to do it.

Assigning a numDer to a numBase will "slice" the object and no longer be the correct type.

In order to get polymorphic behavior, you must use either pointers or references.

The compiler is reporting an error correctly telling you the inc method does not exist on numBase .

Polymorphic methods must be declared in the base class and also declared virtual .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM