1

I am learning C++ from tutorialspoint. In the topic of polymorphism, they have the following code (only relevant parts added):

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); 
      }

I don't understand this line: " Rectangle( int a = 0, int b = 0):Shape(a, b) { }", specifically this part: ":Shape(a, b)". I read earlier that in constructors of a class, we can assign values to the class member variables using the following syntax:

Classname ( type arg1, type arg2, ...) : member_variable1(arg1), member_variable2(arg2), ... {.. }

But here Shape is a constructor (a function) of base class. Moreover, I also read that constructors (along with destructors, overloaded operators and friend functions) cannot be inherited - so how can we use a call to Shape?

Anon
  • 381
  • 1
  • 2
  • 13
  • 1
    Hey there :) The part `: Shape(a, b)` calls the constructor for `Shape` (similar to `super` in JavaScript). I'd recommend you to have a [look at this Stack Overflow answer](https://stackoverflow.com/a/120916/9591441). Hope it helps :) – Ed The ''Pro'' Mar 31 '20 at 22:41

0 Answers0