This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stdio.h> | |
using namespace std; | |
// Base class | |
class Shape | |
{ | |
public: | |
void setWidth(int w) | |
{ | |
width = w; | |
} | |
void setHeight(int h) | |
{ | |
height = h; | |
} | |
Shape() | |
{ | |
printf("creating shape \n"); | |
} | |
Shape(int h,int w) | |
{ | |
height = h; | |
width = w; | |
printf("creatig shape with attributes\n"); | |
} | |
protected: | |
int width; | |
int height; | |
}; | |
// Derived class | |
class Rectangle: public Shape | |
{ | |
public: | |
int getArea() | |
{ | |
return (width * height); | |
} | |
Rectangle() | |
{ | |
printf("creating rectangle \n"); | |
} | |
Rectangle(int h,int w) | |
{ | |
printf("creating rectangle with attributes \n"); | |
height = h; | |
width = w; | |
} | |
}; | |
int main(void) | |
{ | |
Rectangle Rect; | |
Rect.setWidth(5); | |
Rect.setHeight(7); | |
Rectangle *square = new Rectangle(5,5); | |
// Print the area of the object. | |
cout << "Total area: " << Rect.getArea() << endl; | |
return 0; | |
} | |
Output: | |
creating shape | |
creating rectangle | |
creating shape | |
creating rectangle with attributes | |
Total area: 35 |
The default class constructor is called unless you explicitly call another constructor in the derived class. the language specifies this.
Rectangle(int h,int w):
Shape(h,w)
{...}
No comments:
Post a Comment