I'm doing a project for school and I've run into a problem. I have to reset values of a cylinder (height and diameter), back to the values used in the default constructor within a function. Here is what I have so far:

My Class

class cylinder
{
public:
cylinder();
cylinder(double x, double y);
double    get_height();
void      set_height(double height);

double    get_diameter();
void      set_diameter(double diameter);

void      calculate_volume(double height, double diameter);

void      original_cylinder(double height, double diameter);
void      new_cylinder(double height, double diameter);

private:
     struct      a_cylinder
     {
          double    height;
          double    diameter;
     } silly;
};

default constructors:

//default constructor
cylinder::cylinder() 
{
  silly.height = 1.0;
  silly.diameter = 1.0;
}

cylinder::cylinder(double x, double y)
{
  silly.height = x;
  silly.diameter = y;
}

And this is the code I need to fix

void cylinder::original_cylinder(height, diameter)
{
  cylinder();
}

Why can I not call the constructor?

You could do 2 things - hard code or have default variables as constants. I would use hard-coded for now. Which way do you prefer?

Hard-coding is the practice of placing literal constants (e.g., the number 1.0) directly into the program code, rather than holding them in named constants. Repeated use of hard-coded values, or use of inobvious values, is generally frowned upon, as it can make maintenance harder (because if have to change it in the future, you have to know when the number 1.0 refers to the height of a cylinder, as opposed to, say, the angle of an unrelated triangle. What Taywin means here is that you can either have named constants for the two values, or - since they are trivial cases which only appear in two locations - you can simply repeat the default values directly in the original_cylinder() method.

I personally would use named constants, but that's a personal preference.

As for why you can't apply the default c'tor to the existing cylinder object, well, the whole purpose of the constructor is to create and return a new object. You can't replace an object with a new object from a method which is part of the original object itself, if you follow me.

cylinder::reset_cylinder() 
{
  silly.height = DEFAULT_HEIGHT;
  silly.diameter = DEFAULT_DIAMETER;
}

Edited 5 Years Ago by Schol-R-LEA: n/a

This article has been dead for over six months. Start a new discussion instead.