Search code examples
c++classconstructorinitialization

Initialized values do not change / C++


I'm making a program that prints the points and the length of a shape. I initialized points in the constructors of the subclasses and the length in main but still it doesn't show the initialized values that I set.

This is my result: This is a Shape. It has 0 points and length: 1.82804e-322 This is a Shape. It has 1 points and length: 2.102e-317 This is a Shape. It has -1 points and length: 2.10154e-317

This is my code:

#include <iostream>
#include <math.h>
#include <string>
#define pi 3.14159265358979323846

using namespace std;

class Shape {

private:
    int points;
    double length;
    //constructors
protected:
    Shape(int Spoints, double Slength)
    {
        Spoints = points;
        Slength = length;
    }

public:
    Shape(){};
    //methods
    string getClass() { return "Shape"; }
    void printDetails() { cout << "This is a " << getClass() << ". It has " << points << " points and length: " << length << "\n"; }
    double getlength() { return length; }
};

class Rectangle : public Shape {
    //constructors
public:
    Rectangle(double Slength)
        : Shape(4, Slength)
    {
    }

    //getters
    string getClass() { return "Rectangle"; }
    double getArea() { return (getlength() * 2); };
};

class Triangle : public Shape {
    //constructor
public:
    Triangle(double Slength)
        : Shape(3, Slength){};

    //getters
    string getClass() { return "Triangle"; }
    double getArea() { return ((sqrt(3) / 4) * pow(getlength(), 2)); }
};

class Circle : public Shape {
    //consturctor
public:
    Circle(double Slength)
        : Shape(1, Slength)
    {
    }

    //getters
    string getClass() { return "Circle"; }
    double getArea() { return (pow(getlength(), 2) * pi); }
};

int main()
{
    Shape* s;
    Rectangle r(2);
    Triangle t(3);
    Circle c(4);

    s = &r;
    s->printDetails();
    s = &t;
    s->printDetails();
    s = &c;
    s->printDetails();
    return 0;
};

Solution

  • For example the body of the constructor

    protected: Shape(int Spoints, double Slength){
            Spoints = points; 
            Slength = length;
        }
    

    does not make a sense because you are trying to reassign parameters instead of data members of the class.

    You should write

    protected: 
        Shape(int Spoints, double Slength) : points( Spoints ), length( Slength )
        {
        }
    

    Also this default constructor

    Shape(){};
    

    leaves the data members uninitialized.

    Also pay attention to as the function getClass is not virtual there is no polymorphism. You could declare it like

    virtual string getClass() const { return "Shape"; }
    

    and in other derived classes you could override it like for example

    string getClass() const override { return "Rectangle"; }
    

    Also you should make the destructor of the class Shape virtual

    virtual ~Shape() = default;