Polymorphism and use of Constructors

Hey hey,

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
using namespace 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 = &rect;
	//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?

Thanks in advance,
Daniel
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);
  }
};
@gentleguy Yes. I only mentioned the constructor thing since you'd already linked to "virtual", and was addressing
flipflipflip wrote:
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?
that question.
Topic archived. No new replies allowed.