In the main program, I call a function within the base class that sets 2 variables. In the derived class, I have a function that calls on a function within the base class to retrieve and return those variables.
The problem I'm having is that it is not working right, or I'm doing something wrong. What seems to be happening, is that when the function in the derived class calls the base class function, rather than just running, it first seems to run the default constructor, which zeros out the stored variables. Then the function returns the zeros.
Does that make sense? I'm new to C++ so I may be missing something, but from what I've read, in theory, this should work.
It's weird that is happening but could you not write the derived class constructor, to call the base class constructor and set the base class members that way? Then you wouldn't have the problem of it calling the default constructor because you would be specifying what base class constructor to use when you write you're derived class constructor.
derived-constructor(arg-list) : base-constructor(arg-list) {
body of derived constructor
}
I tried to keep the code I'm posting as limited as possible. I'm posting the base class and one of the derived classed as defined in the header files, the default constructor for the base class and the one function in the derived class that is calling on the base class function.
void circleType::print() const //Prints the radius, diameter, area and circumference
{
cout << "The radius of the circle is: " << getRadius() << endl;
cout << "The diameter of the circle is: " << calcDia() << endl;
cout << "The area of the circle is: " << calcArea() << endl;
cout << "The circumference of the circle is: " << calcCir() << endl;
cout << fixed << setprecision(2) << "The x and y coordinates are: ";
cout << getX() << "," << getY() << "." << endl;
}
I had initially made them static because I thought that the stored data was being lost/reset. It was just something I had tried and just hadn't removed yet.
What's the point of lines 31 and 32 in pointType.cpp, 47 in circleType.cpp, and 42 in cylinderType.cpp?
I was trying something. These are the default constructors. I originally had them set to = 0. I thought that if I removed the zero, it would just initialize the variable and retain its original data. I was kind of grasping at straws there.
Between lines 24 and 32, and 34 and 42 of main.cpp you're not setting x or y.
So I need to set x and y each time? Would I just use the same function call that I used initially?
There might be a better way of doing this, possibly as helios suggested, but I'm going to stick with this method for now. It works and I found it in my text book...