C++/class

Advertisement


Question
(c) Use C++ to show the declaration of a class square that derives from rectangle, which in turn derives from shape.

How can Ido?

Thanks!

Answer
Hello Daniel, thank you for the question.

First you start off declaring your Shape class, which would contain all of your basic properties that are common to all shapes. This would probably be an abstract base class. Then you just inherit classes from it, adding the extra properties as needed:

class Shape
{
public:
int x, y;
Shape() {x = y = 0;}
~Shape() = 0;
};

class Rectangle : public Shape
{
public:
int width, height;
Rectangle() {width = height = 0;}
~Rectangle();
};

class Square : public Rectangle
{
public:
Square(int _x=0,int _y=0,int _width=50,int _height=50)
{
x = _x;
y = _y;
if(_width != _height)
std::cout << "Warning, height and width should be the same\n;"
width = _width;
height = _height;
}
};

And that's pretty much it. It follows the inheritence tree, each class adding the variables needed. If you have any other questions, please don't hesitate to ask.

I hope this information was helpful.

- Eddie

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.