How do I cast a parent class as the child class

后端 未结 8 1954
深忆病人
深忆病人 2020-12-29 19:46

It\'s been a while since I have had to write C++ code and I\'m feeling kind of stupid. I\'ve written code that is similar to, but is not exactly, the code b

8条回答
  •  失恋的感觉
    2020-12-29 20:25

    You can cast using Single Argument Constructor: i.e. (A parent works, A child Studies) as follows:

    #include 
    using std::cout;
    
    class Parent
    {
        public:
        void goToWork()
        {
            cout<<"working\n";  // only parents work
        }
    };
    
    class Child : public Parent
    {
        public:
        Child(const Parent& parentAddr){}
        void goToSchool()
        {
            cout<<"studying\n";   // only children studies
        }
    };
    
    int main(void)
    {
        Child child(*(new Parent()));
    
        // here's a child working
        child.goToWork();
        return 0;
    }
    

    you pass an child class address as parent's constructor parameter and you can use a child obj to do parent's stuff

提交回复
热议问题