I came across this tutorial link when studying OOPS concepts in C++. http://www.tutorialspoint.com/cplusplus/cpp_polymorphism.htm
In the base class Shape
, it has constructor with two parameters to set its protected variables and in main()
I thought the only way to create an object for class Shape
is by doing something like Shape shape(2,4)
to match the constructor in Shape
class.
Can someone say how the instantiation Shape *shape
without any parameters work and whats the difference between creating object by Shape shape(2,4)
and Shape *shape
.
#include <iostream>
using namespace std;
class Shape{
protected:
int w,h;
public:
Shape(int a, int b){
w=a;
h=b;
}
int area(){
cout << "Shape class area" << endl;
return 0;
}
};
class Rect:public Shape{
public:
Rect(int a, int b):Shape(a,b) {}
int area(){
cout <<"Rect class area " << endl;
return w*h;
}
};
class Tri:public Shape{
public:
Tri(int a, int b):Shape(a,b) {}
int area(){
cout << "Tri class area" << endl;
return (w*h)/2;
}
};
int main(){
Shape *shape;
Rect r(4,5);
Tri t(4,5);
shape=&r;
shape->area();
shape=&t;
shape->area();
return 0;
}
Statement
Shape *shape;
does not create any instance of the class Shape.
It declares a variable that is a pointer of type Shape *
and that is not initialized that is it has indetermined value provided that the declaration declares a local variable.
As for the constructor then the only constructor of the class with two parameters is also the default constructor of the class because each parameter has a default argument.
Shape( int a=0, int b=0)
^^^ ^^^
{
//...
}
Thus you can write for example
Shape sh;
and data members of the created object will be initialized by these default arguments. This declaration is equivalent to
Shape sh( 0, 0 );