Search code examples
c++c++11abstract-classpure-virtual

Can Abstract class have constructor and private member in C++11


Similar questions are asked but they do not give answer to my question. I am trying to create Abstract class (with one pure virtual function). But compiler gives this error:

src/library.cpp:11:24: error: invalid cast to abstract class type ‘mgc::Shapes’ Shapes(length, name);

I have constructor of Abstract class as it has member variables and member functions. I have no idea why this error is coming..

Here is my header file librar.h

class Shapes
{
public:
    Shapes(double len = 0.0, std::string name = "");
    virtual void printClass();
    virtual double area() = 0;
protected:
    double len_, width_;
    std::string name_;
};

class Triangle : public Shapes
{
public:
    Triangle(double lene =0, std::string namee= "" );
    void printClass();
    double area();
};

Here is my implementation file library.cpp

mgc::Shapes::Shapes(double length, std::string name)
: len_(length),
 width_(length),
name_(name)
{}

mgc::Triangle::Triangle(double length, std::string name)
{
    Shapes(length, name);
}

void mgc::Shapes::printClass()
{
    std::cout<<"Base class is called"<<std::endl;
}

void mgc::Triangle::printClass()
{
    std::cout<<"Triangle class is called"<<std::endl;
}

double mgc::Triangle::area()
{
    return(width_*len_);
}

Solution

  • Triangle constructor should invoke base class constructor inside of initialization list:

    mgc::Triangle::Triangle(double length, std::string name)
    :   Shapes(length, name)
    {
    }