why cant I make square take one perimeter whilst rectangle takes two?
Aug 17, 2018 at 3:26pm UTC
My book is asking me to make the rectangle class constructor just take length whilst making rectangle take width and lenght , how do i get it to compile?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#include<iostream>
class Shape
{
public :
Shape(){}
~Shape(){}
protected :
};
class Rectangle : public Shape
{
public :
virtual Rectangle(int length, int width){}
virtual ~Rectangle(){}
protected :
int length, width;
};
class Square : public Rectangle
{
public :
virtual Square(int length){}
virtual Square(const Square &){}
virtual ~Square(){}
int getLength(){return length;}
protected :
int length;
};
int main()
{
Square Object(5);
std::cout << "The length is << " <<Object.getLength()<<std::endl;
}
~
~
~
~
~
"q2ch11.cpp" 35L, 501C 23,26 All
Aug 17, 2018 at 3:52pm UTC
Square's constructor calls Rectangle's constructor. If you don't tell Square's constructor which of Rectangle's constructors to call, it tries to call the default constructor (which doesn't exist).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include<iostream>
class Shape
{
public :
Shape(){}
virtual ~Shape(){}
};
class Rectangle : public Shape
{
public :
Rectangle(int inputlength, int inputwidth) : length(inputlength), width(inputwidth){}
~Rectangle(){}
protected :
int length, width;
};
class Square : public Rectangle
{
public :
Square(int length) : Rectangle(length, length){} // Calls Rectangle(int inputlength, int inputwidth)
Square(const Square & other) : Rectangle(other.length, other.length) {} // Calls Rectangle(int inputlength, int inputwidth)
~Square(){}
int getLength(){return length;}
};
int main()
{
Square Object(5);
std::cout << "The length is << " <<Object.getLength()<<std::endl;
}
Last edited on Aug 17, 2018 at 3:53pm UTC
Aug 17, 2018 at 6:07pm UTC
Constructors cannot be virtual. Destructors can be virtual and probably should be in this case.
Aug 17, 2018 at 6:45pm UTC
The "virtual" mechanism doesn't come into effect unless you use pointers or references to the base class(es).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
class Shape {
public :
virtual ~Shape() = default ;
virtual int area() = 0;
};
class Rect : public Shape {
int length, width;
public :
Rect(int length, int width) : length(length), width(width) {}
int area() { return length * width; }
};
class Square : public Rect {
public :
Square(int side) : Rect(side, side) {}
};
#include <iostream>
int main() {
Shape *sh = new Square(10);
std::cout << sh->area() << '\n' ;
delete sh;
}
Last edited on Aug 17, 2018 at 6:47pm UTC
Topic archived. No new replies allowed.