a few days ago i started looking into C++ and since im familiar with some programming concepts I tried using a quickguide.
Im currently stuck at Polymorphism or rather at the usage of constructors. The main purpose of that chapter is to circumvent early binding by using "virtual" keyword which makes perfect sense. There is one tiny detail that is driving me mad though:
#include <iostream>
usingnamespace std; //bad practice, i know :p
class Shape
{
protected:
int width, height;
public:
Shape(int a=0,int b=0)
{
width = a;
height = b;
}
int area()
{
cout << "Parent class area :" << endl;
return 0;
}
};
class Rectangle: public Shape
{
public:
Rectangle(int a=0,int b=0)
{
Shape(a,b);
}
int area()
{
cout << "Rectangle class area :" << endl;
return (width*height);
}
};
// Main function for the program
int main()
{
Shape *shape;
Rectangle rect(10,8);
Triangle tri(10,5);
//store the address of Rectangle
shape = ▭
//call rectangle area
shape->getArea();
return 0;
}
The code is working fine, but the width and height of my rectangle is always set to 0 (which makes perfect sense, judging by the code). Whenever I start to change the Constructor parameters to this (so it should use the actual values im calling the Constructor with, not just overwrite them to 0 instantly)
1 2
Shape(int a,int b)
Rectangle(int a,int b)
following compiling error occurs: "no matching function for call to 'Shape::Shape()'"
Its really driving me mad since I know I screwed up somewhere cause this clearly cant be the purpose of Polymorphism.
What can I do to fix this problem and create a Rectangle Object which uses the Parent Class' Constructor and the actual values I want it to use?
Try invoking the parent constructor in the initialization list
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class Rectangle : public Shape
{
public:
Rectangle(int a = 0, int b = 0) : Shape(a, b)
{
//Shape(a, b);
}
int area()
{
cout << "Rectangle class area :" << endl;
return (width*height);
}
};