Click here to Skip to main content
15,890,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Here is the code.

This code is to understand the concept of virtual function so in the constructor when write like shape(int a=0, int b=0 ) and same for all other constructor of derived classes, working absolutely fine.
But when not initializing the members to 0 it's showing error like " no matching function for call to Shape::Shape()".
C++
#include< iostream >
using namespace std;
class Shape {
protected:
    int width, height;
    int mem;
public:
    Shape( int a, int b)
    {
        width = a;
        height = b;
    }
    virtual int area()
    {
        cout << "Parent class area :" <<endl;
        return 0;
    }
    virtual int dis()
    {
        mem=0;
    }
};
class Rectangle: public Shape{
public:
    Rectangle(int a, int b)
    {
        Shape(a, b);
    }
    int area ()
    {
        cout << "Rectangle class area :" <<endl;
        return (width * height);
    }
    int dis()
    {
        cout<<"mem is : "<<mem<<endl;
    }
};
class Triangle: public Shape{
public:
    Triangle(int a, int b)
    {
        Shape(a, b);
    }
    int area ()
    {
        cout << "Triangle class area :" <<endl;
        return (width * height / 2);
    }
};
// Main function for the program
int main( )
{
    Shape *shape;
    Rectangle rec(10,7);
    Triangle  tri(10,5);
    // store the address of Rectangle
    shape = &rec;
    // call rectangle area.
    shape->area();
    shape->dis();
    // store the address of Triangle
    shape = &tri;
    // call triangle area.
    shape->area();

    return 0;
}
Posted
Updated 29-Sep-13 9:02am
v6

1 solution

Bug #1:
You are allowed to call the constructor of a member variable or base class only from the initializer list of your constructor.
C++
Rectangle(int a, int b)
    : Shape(a, b)
{
}


Bug #2:
"no matching function for call to Shape::Shape()"
If you don't explicitly call the constructor of Shape from your derived class then the compiler automatically calls the default (parameterless) constructor of the base class. The problem with this is that your Shape class doesn't have a default constructor because the compiler auto-generates a default constructor only if you don't provide any other constructors. If you define your own constructors then the class will have a default constructor only if you write one for it.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 29-Sep-13 23:40pm    
Sure, 5ed.
—SA
pasztorpisti 30-Sep-13 4:27am    
Thank you!
Captain Price 1-Oct-13 7:25am    
This answer should be marked as "Accepted"

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900