简体   繁体   中英

C++ Polymorphism Error

I am using Polymorphism in C++ to create a basic 'family' in polymorphism. However, I get the errors, when trying to create the son boo: error C2512: 'Son' : no appropriate default constructor available and error C2660: 'Son::Son' : function does not take 2 arguments , which confuse me, as they are both parts of the Child class, which takes two arguments

#include <iostream>
class Parent{
public:
    Parent(char* name) : Name(name){};
    char* Name;
    void Speak(void){
        std::cout << "I am a parent called " << Name << std::endl;
    }
};
class Child{
public:
    Child(Parent* parent, char* name) : par(parent), Name(name){};
    Parent* par;
    char* Name;
    virtual void Speak(void){
        std::cout << "I am a child, my name is " << Name << " and my parent's name is " << par->Name << std::endl;
    }
};
class Son : public Child{
public:
    void Speak(void){
        std::cout << "I am a son, my name is " << Name << " and my parent's name is " << par->Name << std::endl;
    }
};
int main(void){
    Parent Dad = Parent("James");
    Child Lisa = Child(&Dad, "Lisa");
    Son Boo = Son(&Dad, "Boo"); // Error here
    Dad.Speak();
    Lisa.Speak();
    Boo.Speak();
    getchar();
    return (0);
}

As the compiler points out, you haven't provided a valid constructor for the Son Class. Try:

Son(Parent* parent, char* name) : par(parent), Name(name){};

EDIT: As dasblinkenlight pointed out, since here the Son does not have any members of its own to initialize, you should directly reference Child Class's constructor.

Son(Parent* parent, char* name) : Child(parent, name) {}

This is because your Son class that has no user-defined constructors is derived from Child , which has a user-defined constructor, and does not have a constructor that can be called with no parameters.

When C++ constructs an object, a constructor must be called. If you do not define a constructor, compiler defines one for you if it can. In this case, it cannot do it, because it does not know what to pass to the constructor of your base class.

Adding a constructor to Son that initializes the Child properly should fix this problem:

Son(Parent* parent, char* name) : Child(parent, name) {}

When deriving from a base class, constructors are not inherited .

That is why you must provide a constructor for Son

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