-2

So i know that new and delete implicitly call constructor but i couldn't get my head around how window(new rectangle (30, 20)) is working.

#include <iostream>
using namespace std; 

class Rectangle
{    
     private:
         double height, width;
     public:
         Rectangle(double h, double w) {
             height = h;
             width = w;
         }
         double area() {
         cout << "Area of Rect. Window = ";
         return height*width;
         }
};

class Window 
{
    public: 
        Window(Rectangle *r) : rectangle(r){}
        double area() {
            return rectangle->area();
        }
    private:
        Rectangle *rectangle;
};


int main() 
{
    Window *wRect = new Window(new Rectangle(10,20));
    cout << wRect->area();

    return 0;
}
Mistalis
  • 17,793
  • 13
  • 73
  • 97
Muku
  • 538
  • 4
  • 18

1 Answers1

0

Window's constructor takes one parameter, a pointer to a Rectangle.

new Rectangle(10,20)

This expression constructs a new instance of the Rectangle class, giving you a pointer to the new class instance.

So:

Window *wRect = new Window(new Rectangle(10,20));

After obtaining a pointer to the new instance of the Rectangle class, the pointer gets passed to Window's constructor, for a new instance of the Window class.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148