Home > OS >  Can't update values of members when constructor is invoked
Can't update values of members when constructor is invoked

Time:06-07

I've created two classes, 'Cylinder' and 'random', with 'Cylinder' publicly inherited by 'random'. So I created an object of 'random' and tried to change values of member variables of "Cylinder'. Couldn't get it to work

#include "constants.h"
#include<iostream>
class Cylinder{
  public:
    double r,h;
    
  public:
  int *x;
  Cylinder(){
      r = 2.0;
      h = 2.0;
      x = new int(1);
      std::cout<<"\nConstructor Invoked!";
  };
  Cylinder(double radius, double height){
      r= radius;
      h = height;
      std::cout<<"Constructor Invoked!";
  };
   
    void display(){
        std::cout<<"\n"<<"Radius:"<<r<<"\nHeight:"<<h;
    }
    ~Cylinder(){
        delete x;
        std::cout<<"\nDestructor Invoked!";
    }
};
class random : public Cylinder
{
    
    public:
        random() = default;
        random(double r,double h)
        {
           **Cylinder(r,h);**
        }
        void disp_cy()
        {
            display();
        }
};

Main:
#include "cylinder.h"
#include<iostream>

int main()
{
    **random R1(10.0,10.0);**
    R1.disp_cy();
}

Output: Constructor Invoked!Constructor Invoked! Destructor Invoked! Radius:2 Height:2 Destructor Invoked!

CodePudding user response:

You need to delegate to the superclass constructor in the member initializer list for your constructor, not in the body of the constructor itself:

random(double r,double h) : Cylinder(r, h) {}

As is, the default superclass constructor got invoked implicitly (thus seeing default values on your random instance), and the Cylinder(r, h) in the body of the constructor just created a brand new Cylinder that was immediately thrown away.

CodePudding user response:

your code is creating a new cyclinder that has nothing to do with the cylinder in the inheritance tree of random

    random(double r,double h)
    {
       **Cylinder(r,h);** << just some random variable 
    }

also note that you have UB, the member field x is not initialized in the constructor that takes arguments, but then you delete it

  • Related