Your code:
class Triangle: public Shape{
public:
Triangle(int a=0, int b=0):Shape(a,b)
{
// may do something
}
int area()
{
cout << "in triangle class";
return width*height/2;
}
};
How does internally work:
class Triangle: public Shape{
public:
Triangle(int a=0, int b=0):
{
// always before the others instructions
base(a,b);
// may do something
}
int area()
{
cout << "in triangle class";
return width*height/2;
}
};
There are several ways to work with constructors:
(1) Declare a new class with a new constructor
class NewConstructorClass: public SomeBaseClass // dont care about parent class constructor
{
NewConstructorClass {
// do something new instruction 1
// do something new instruction 2
// do something new instruction 3
}
public:
void DoAnything()
{
// ...
}
};
(2) Declare a new class with a new and empty, constructor. Some developers do this, in order, to add code to the constructor, later, or, explicitly, add an empty constructor, as a "best practice", to indicate that there should be a constructor.
class NewConstructorClass: public SomeBaseClass // dont care about parent class constructor
{
NewConstructorClass {
// does nothing, on purpouse
}
public:
void DoAnything()
{
// ...
}
};
(3) Declare a new class without a new constructor. The compilers adds an automatic constructor that does nothing.
class NewConstructorClass: public SomeBaseClass // dont care about parent class constructor
{
NewConstructorClass {
// do something new
}
public:
void DoAnything()
{
// ...
}
};
(4) Declare a new class with a new constructor, that calls the base constructor. Like your scenario:
class NewConstructorClass: public SomeBaseClass // dont care about parent class constructor
{
NewConstructorClass: base() {
// do something new
}
public:
void DoAnything()
{
// ...
}
};
Each case, depends, on what you want to achieve. Some of this cases, may be consider "Bad practices", others "good practices", depending on coding styles.
Cheers.