Program To Create A Dynamic Object Using A Reference Variable In C++

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code

Code


To copy code: Click View Source “View Source” on the right of this code snippet.


Background and Explanation of the code


In the above program, the subpart new rectangle in the statement

rectangle &r1 = *(new rectangle);

creates a nameless dynamic object of type rectangle and returns the pointer to this object.In order to retrieve the original object we use asterik (*) followed by new rectangle enclosed in parentheses to dereference it.So to refer this nameless object its reference r1 is created which can be used as a normal object for calling read ( ) and area ( ) member functions using dot operator(.).

OUTPUT

Constructor with no parameter invoked

Enter length and breadth = 3   5

Area of rectangle =  15

End of program