multilevel inheritance without calling superclass constructor - c++

I have created three class: Square, Rectangle and Polygon. Square is inheriting from Rectangle and Rectangle is inheriting from Polygon.
The problem is that whenever I call Square constructor, Rectangle constructor get called and I get an error. How can I solve this?
#include <iostream>
using namespace std;
// Multilevel Inheritance
class Polygon
{
protected:
int sides;
};
class Rectangle: public Polygon
{
protected:
int length, breadth;
public:
Rectangle(int l, int b)
{
length = l;
breadth = b;
sides = 2;
}
void getDimensions()
{
cout << "Length = " << length << endl;
cout << "Breadth = " << breadth << endl;
}
};
class Square: public Rectangle
{
public:
Square(int side)
{
length = side;
breadth = length;
sides = 1;
}
};
int main(void)
{
Square s(10);
s.getDimensions();
}
If I comment out the Rectangle constructor, everything works fine. But I want to have both constructors. Is there anything I can do?

You should not set members of a base class in a derived class constructor. Instead, call the base class constructor explicitly:
class Polygon
{
protected:
int sides;
public:
Polygon(int _sides): sides(_sides) {} // constructor initializer list!
};
class Rectangle: public Polygon
{
protected:
int length, breadth;
public:
Rectangle(int l, int b) :
Polygon(2), // base class constructor
length(l),
breadth(b)
{}
};
class Square: public Rectangle
{
public:
Square(int side) : Rectangle(side, side)
{
// maybe you need to do this, but this is a sign of a bad design:
sides = 1;
}
};

constructor should be
Square(int side) : Rectangle(side, side) { sides = 1; }
as Rectangle has no default constructor.

Related

Access entire base class from derived class C++

I understand that you can access members of the base class from a derived class, however, I have a function that requires a pointer to my base class as a whole. For example:
#include <iostream>
using namespace std;
function foo(Shape &s){
//does something
}
// Base class
class Shape {
public:
Shape(int w = 100, int h = 100){
width = w;
height = h;
}
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape {
public:
Rectangle(){
Shape();
}
int getArea() {
return (width * height);
}
};
int main(void) {
Rectangle Rect;
foo(// Pointer Reference to Rect.Shape here);
return 0;
}
Is there any way to get a pointer to this base class from the derived class?
Here's a working version of your code. I made some changes to it and added comments to explain the changes. Your program requires polymorphism to behave as expected, otherwise you'll 'slice' your derived object and just have a Base object.
#include <iostream>
#include <string>
// Base class
// Your base should only have things that would be common to all derived classes
// Consider what the width and height of a Circle would be
//
// You may not have gotten to virtual functions and polymorphism yet. This is
// how you would set up an interface for your Derived classes. I am requiring
// any derived class to implement getArea() and identify() if it wants to be a
// 'concrete' class. Otherwise it will be abstract, which means you can't
// declare objects of that type. It is not possible to declare a Shape object
// because of the pure virtual functions
class Shape {
public:
virtual ~Shape() = default; // A virtual destructor is required
virtual double getArea() const = 0; // Pure virtual function
virtual std::string identify() const = 0;
};
// Derived class
class Rectangle : public Shape {
public:
// The base class should be initialized in the constructor's
// initialization section. What you did was declare a temporary Shape that
// went away when the function ended.
// All class data should be set in the initialization section
Rectangle(int w, int h) : Shape(), width(w), height(h) {}
double getArea() const override { return (width * height); }
std::string identify() const override { return "Rectangle"; }
private:
int width = 0;
int height = 0;
};
// A new derived class that should work (a circle **is-a** shape), but doesn't
// with your setup. Circles don't have width and height
class Circle : public Shape {
public:
Circle(int r) : Shape(), radius(r) {}
double getArea() const override { return 2 * 3.14 * radius * radius; }
std::string identify() const override { return "Circle"; }
private:
int radius = 0;
};
// Subjective, I moved the function below the class definitions and added a body
void foo(Shape &s) {
std::cout << "A " << s.identify() << " with area " << s.getArea() << ".\n";
}
int main(void) {
Rectangle rect(5, 3);
foo(rect);
Circle circ(4);
foo(circ);
return 0;
}
Output:
A Rectangle with area 15
A Circle with area 100.48
If I remove all the virtual stuff, a lot of things stop working. I now have to provide implementations for the Shape functions. That logically doesn't make much sense. And while I can pass my derived objects to foo(), they get sliced, and the filler Shape data gets printed instead.

Making a vector of base class pointers and pass Derived class objects to it (Polymorphism)

I'm trying to implement a menu for my Shape program. I've implemented all of the shapes classes. Two are deriving straight from the abstract class "Shape", and two others are deriving from a class called "Polygon" which derives from "Shape" as shown bellow:
Shape -> Polygon -> Rectangle, Triangle
`-> Circle, Arrow
In my menu class, I want to create some sort of an array that can contain the pointers to the objects and with the type of the base class "Shape". But I'm not sure how to do it properly and in a way which will work for all of my shapes, because 2 of my classes aren't deriving from "Shape" directly.
This is my menu class:
class Menu
{
protected:
//array of derived objects
public:
Menu();
~Menu();
// more functions..
void addShape(Shape& shape);
void deleteAllShapes();
void deleteShape(Shape& shape);
void printDetails(Shape& shape);
private:
Canvas _canvas; //Ignore, I use this program to eventually draw this objects to a cool GUI
};
And in the function "addShape(Shape& shape);", Which I want to use to add each given shape to my array. How can I implement the addition of new objects to it? And also, how can I check if the given object is deriving from "Polygon" or not? Because if so then I need to call the member functions differently as far as I understand.
I see that you have an array in Menu, let's say:
Shape* myshapes[10];
The shapes can be Rectangles, Triangles, Circles etc.
What you want is to be able to use the Menu's printDetails() method like this:
void printDetails()
{
for(int i = 0; i < size; i++)
{
cout << "Index " << i << " has " << myshapes[i]->getShapeName() << endl;
}
}
The getShapeName() will return a string, e.g. "Rectangle" if it is Rectangle.
You will be able to do this with the help of pure virtual function. The pure virtual function must be in the abstract class Shape, which has:
virtual string getShapeName() = 0; //pure virtual
It means that we are expecting a definition for this function in the derived class. This way you will be able to use getShapeName() method using the Shape pointers in the shapes array, which will tell you whether the shape is Rectangle, Triangle, or Circle etc.
class Shape
{
public:
virtual string getShapeName() = 0;
};
class Circle : public Shape
{
private:
int radius;
public:
Circle(int r) { radius = r; cout << "Circle created!\n"; }
string getShapeName() { return "Circle"; }
};
class Arrow : public Shape
{
private:
int length;
public:
Arrow(int l) { length = l; cout << "Arrow created!\n"; }
string getShapeName() { return "Arrow"; }
};
class Polygon : public Shape
{
public:
virtual string getShapeName() = 0;
};
class Triangle : public Polygon
{
private:
int x, y, z;
public:
Triangle(int a, int b, int c) { x = a; y = b; z = c; cout << "Triangle created!\n"; }
string getShapeName() { return "Triangle"; }
};
class Rectangle : public Polygon
{
private:
int length;
int width;
public:
Rectangle(int l, int w){ length = l; width = w; cout << "Rectangle created!\n"; }
string getShapeName() { return "Rectangle"; }
};
To implement the addShape() method you can do this:
void addShape(Shape &shape)
{
myshapes[count] = &shape;
count++;
}
Also, keep in mind to pass the Shape by reference or by using pointer, in the addShape() method.
I hope this helps... Best of luck :-)

How to copy polymorphic object

The function "foo" is from external library (In my case DEAlII ).
It takes in class type as template parameter and its object. It then creates a copy of this object and performs some operation on this object.
The problem is when the input class is polymorphic (template ). Then I always pass base class object but pointing to different derived class, but the copied object in the function "foo" will be base class.
And any call to member function on this copied object will call base class member function(But I need them to call to corresponding derived class member function).
Additionally the type of derived class is decided at runtime based on some input parameter. I cannot change/ move to different library, but I should be able to modify the function "foo" in the library(preferably not but may be as a last resort).
#include <iostream>
#include <memory>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0){
width = a;
height = b;
}
void set(int a){
width =a ;
}
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
virtual ~Shape()=default;
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }
int area () override{
cout << "Rectangle class area :" <<width*height <<endl;
return (width * height);
}
};
class Triangle: public Shape {
public:
Triangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
Triangle(const Triangle &triangle){
width = triangle.width;
height = triangle.height;
}
};
template <class temp>
void foo (temp &shape){
shape.area();
temp shape_sample = shape;
shape_sample.area();
}
// Main function for the program
int main() {
unique_ptr<Shape> shape;
Rectangle rec(10,7);
shape =make_unique<Rectangle> (rec);
foo (*shape.get());
shape->area();
return 0;
}
If the implementation of foo can't be change then I see two options here:
Option 1: Simply downcast to appropriate type if you know what it is:
foo(static_cast<Rectangle &>(*shape.get()));
Option 2 (overkill): hide the polymorphism using Bridge pattern:
class Shape {
protected:
class ShapeImpl {
public:
int width, height;
virtual ~ShapeImpl() = default;
// "virtual copy constructor" which you could've used without a Bridge
// if you could change "foo"
virtual ShapeImpl *clone() { return new ShapeImpl(*this); }
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
} *impl; // can't use unique_ptr because we want copy
Shape(ShapeImpl *impl)
: impl(impl) { }
public:
Shape(const Shape &other)
: impl(other.impl ? other.impl->clone() : nullptr) {
}
Shape(Shape &&other)
: impl(nullptr) {
std::swap(impl, other.impl);
}
virtual ~Shape() {
delete impl;
}
// copy-and-swap idiom with one assignment operator to "rule-of-five them all"
Shape &operator=(Shape other) {
std::swap(impl, other.impl);
return *this;
}
int area() {
return impl->area();
}
};
class Rectangle : public Shape {
protected:
class RectangleImpl : public ShapeImpl {
public:
ShapeImpl *clone() override { return new RectangleImpl(*this); }
int area() override {
cout << "Rectangle class area :" <<width*height <<endl;
return (width * height);
}
};
public:
Rectangle(int width = 0, int height = 0)
: Shape(new RectangleImpl())
{
impl->width = width;
impl->height = height;
}
};
If the implementation of the foo could not be changed. one other option is to write a wrapper around it and using dynamic cast send the right type to it.
template <class temp>
void foo (temp &shape)
{
shape.area();
temp shape_sample = shape;
shape_sample.area();
}
void fooWrapper(Shape* shape)
{
Rectangle* shape1 = dynamic_cast<Rectangle*>(shape);
if (shape1)
{
foo<Rectangle>(*shape1);
return;
}
Triangle* shape2 = dynamic_cast<Triangle*>(shape);
if(shape2)
{
foo<Triangle>(*shape2);
return;
}
shape->area();
return;
}
// Main function for the program
int main() {
unique_ptr<Shape> shape;
Triangle tri(10,7);
shape =make_unique<Triangle> (tri);
fooWrapper(shape.get());
Rectangle rec(10,7);
shape = make_unique<Rectangle> (rec);
fooWrapper(shape.get());
return 0;
}`

C++ inherit from a concrete class to another concrete class

I'm trying to inherit from one of my class 2 variables which they must be equal to be able to return the value of one of my functions in the other class..
class Rectangle: public Shape{
double Length;
double Width;
public:
Rectangle(double Length, double Width):
Shape("Rectangle")
{
this->Length=Length;
this->Width=Width;
}
double getPerimerter(){
return 2 * (Length+Width);
}
double getArea(){
return Length * Width;
}
};
class Square: public Shape, public Rectangle{
double Side;
public:
Square():
Shape("Square"),
Rectangle(Length,Width)
{}
double getPerimerter(){
if(Length==Width)
return 4 * (Length+Width);
}
double getArea(){
if(Length==Width)
return (Length+Width) * (Length+Width);
}
};
as you can see I have already a concrete class call Rectangle which hold to private variables with the names Length and Width.. What I'm trying to do is inherit this class to my class Square and if Length and Width are equal then I can return the Area and Perimeter of the Square..
It is perfectly fine to inherit from an existing class.
What you probably want, however, is this:
class Square: public Rectangle
{
public:
Square(double Side) : Rectangle(Side, Side) { }
};
That way, there is no problem of someone trying to use a ractangular square Square(4.3, 9.6).
Alternatively, you could of course use typedef Rectangle Square;
Edit:
To overcome the "name", we could do something like this:
class Rectangle
{
public:
Rectangle(double Length, double Width) : Shape("Rectangle") { ... }
protected:
Rectangle(double Length, double Width, const char *name) : Shape(name), Length(Length), Width(Width) {}
};
class Square
{
public:
Square(double side) : Rectangle(side, side, "Square") {}
};
Edit2: Code that I came up with:
#include <iostream>
using namespace std;
class Shape
{
private:
const char *name;
public:
Shape(const char *name) : name(name) {}
virtual double getPerimeter() = 0;
virtual double getArea() = 0;
};
class Rectangle: public Shape{
double Length;
double Width;
public:
Rectangle(double Length, double Width):
Shape("Rectangle")
{
this->Length=Length;
this->Width=Width;
}
double getPerimeter(){
return 2 * (Length+Width);
}
double getArea(){
return Length * Width;
}
protected:
Rectangle(double Length, double Width, const char *name):
Shape(name)
{
this->Length=Length;
this->Width=Width;
}
};
class Square: public Rectangle
{
public:
Square(double Side):
Rectangle(Side,Side, "Square")
{
}
};
int main()
{
Square sq(10.0);
Rectangle rect(12.0, 4.0);
cout << "sq:" << sq.getArea() << " rect:" << rect.getArea() << endl;
}
As a first thing you should add an argument to Square constructor, like so:
Square(double Side):Rectangle(Side,Side){
// Add additional constructor code here if required
}
About returning a value in a constructor - that is a no-go as the constructor might not return anything.
I hope this is what you meant as your question was quite hard for me to understand.
I might not understand your question, but it looks to me like you only need to add a parameter to your Square() constructor. It would look like this:
class Square: public Rectangle{
public:
Square(double dimension):
Rectangle(dimension, dimension){
}
};
There is no need for a conditional statement in the Square() constructor. Creating a Square necessarily implies creating a Rectangle with equal length and width.

Nested Classes variable calls

I want to go from this:
To this:
How would I do this? How would the functions of subclasses square and rectangle know to use the variable of the parent class shape?
How would I set length and width from main?
#include <iostream>
#include <cmath>
using namespace std;
class SHAPES
{
public:
class SQUARE
{
int perimeter(int length, int width)
{
return 4*length;
}
int area(int length, int width)
{
return length*length;
}
};
public:
class RECTANGLE
{
int perimeter(int length, int width)
{
return 2*length + 2*width;
}
int area(int length, int width)
{
return length*width;
}
};
};
I recommend other (better?!) format:
class Shape
{
protected:
int length,width;
public:
Shape(int l, int w): length(l), width(w){}
int primeter() const
{
return (length + width) * 2;
}
int area() const
{
return length * width;
}
};
class Rectangle : public Shape
{
public
Rectangle(int l, int w) : Shape(l,w){}
};
class Square : public Shape
{
public:
Square(int l): Shape(l,l){}
};
int main()
{
Rectangle r(5,4);
Square s(6);
r.area();
s.area();
}
Or use interface with virtual function.
Those are not subclasses (i.e. derived classes), but rather nested classes (as the title of your question says).
I don't think I would answer your real question if I were to tell you how to make those variables visible in nested classes. Based on what I can understand from the names of your classes, you should rather use inheritance to model the IS-A relation between them:
class SHAPE
{
public: // <-- To make the class constructor visible
SHAPE(int l, int w) : length(l), width(w) { } // <-- Class constructor
...
protected: // <-- To make sure these variables are visible to subclasses
int length;
int width;
};
class SQUARE : public SHAPE // <-- To declare public inheritance
{
public:
SQUARE(int l) : SHAPE(l, l) { } // <-- Forward arguments to base constructor
int perimeter() const // <-- I would also add the const qualifier
{
return 4 * length;
}
...
};
class RECTANGLE : public SHAPE
{
// Similarly here...
};
int main()
{
SQUARE s(5);
cout << s.perimeter();
}