Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherited member from an abstract class can't be initialized by the inherited constructor

class CarPart
{
public:
    CarPart(): name(""), price(0) {}
    virtual int getPrice() = 0;//{return price;}
protected:
    int price;
    string name;
};

class Tire: public CarPart
{
public:
    virtual int getPrice() {return price;}
    Tire(): CarPart(), name("Tire"), price(50)
    {}
};

Visual 2010 tells me name and price are not members of deriv, but they are inherited (error c2614). What am I doing wrong ?

like image 710
jokoon Avatar asked Dec 17 '10 15:12

jokoon


People also ask

Can an abstract class have a constructor in C++?

CPP. 4) An abstract class can have constructors. For example, the following program compiles and runs fine.

Can constructor be inherited in C++?

Constructor is automatically called when the object is created. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can derive from several(two or more) base classes. The constructors of inherited classes are called in the same order in which they are inherited.

How constructors are implemented when the classes are inherited?

When classes are inherited, the constructors are called in the same order as the classes are inherited. If we have a base class and one derived class that inherits this base class, then the base class constructor (whether default or parameterized) will be called first followed by the derived class constructor.

Should abstract base class have constructor?

Constructor is always called by its class name in a class itself. A constructor is used to initialize an object not to build the object. As we all know abstract classes also do have a constructor.


1 Answers

You cannot initialize members that is not an immediate member of your class. n is not an immediate member of deriv, it's an immediate member of base.

However, n is accessible to deriv, so you can always assign it in your deriv constructor, but you should really initialize it in the base constructor.

Also, you can't have virtual constructors. Did you mean to use virtual destructors?

class base
{
public:
    base() : n(0) {} // Are you sure you don't want this?
    virtual void show() = 0;
protected:
    int n;
};

class deriv : public base
{
public:
    deriv() 
    {
        n = 0;
    }

    virtual void show() {}
};

EDIT (A response to the OP's edit): You don't need virtual methods for this:

class CarPart
{
public:
    CarPart(const char* newName, int newPrice) : name(newName), price(newPrice) {}

    const std::string& GetName() const { return name; }
    int GetPrice() const               { return price; }
private:
    std::string name;
    int price;
};

class Tire : public CarPart
{
public:
    Tire() : CarPart("Tire", 50) {}
};

Assuming that all your CarParts has to have a name and a price, this should be more than sufficient.

like image 180
In silico Avatar answered Oct 15 '22 19:10

In silico