I am new to C++. Well I have box.cpp and circle.cpp files. Before I explain my problem I'd like to give you their definitions:
In box.cpp
class Box
{
private:
int area;
public:
Box(int area);
int getArea() const;
}
In circle.cpp
#include "box.h"
class Circle
{
private:
int area;
Box box;
public:
Circle(int area, string str);
int getArea() const;
const Box& getBoxArea() const;
}
Now as you can see in the Circle class I have an integer value and Box object. And in Circle constructor I assign that integer values easily to area.
One problem is that I am given a string for assigning it to the Box object
So what I did inside the Circle constructor is that:
Circle :: Circle(int area, string str)
{
this->area = area;
// here I convert string to an integer value
// Lets say int_str;
// And later I assign that int_str to Box object like this:
Box box(int_str);
}
My intention is to access both Circle area value and Circle object area value. And Finally I write the function const Box& getBoxArea() const; Like this:
const Box& getBoxArea() const
{
return this->box;
}
And as a result I do not get the correct values. What am I missing here?
I would suggest writing a non-member function that calculated the
int
based on the input string, and then use that inCircle
's constructor initialization list.then
You can only initialize a non-static data member in the initialization list. Once you get into the constructor body, everything has been initialized for you and all you can do is perform modifications to the data members. So one variant of your code which would compile if
Box
had a default constructor would beIn constructor of
Circle
you are trying to create an instance ofBox
, which is too late because by the time the body of constructor will be executed, the members ofCircle
shall be constructed already. ClassBox
either needs a default constructor or you need to initializebox
in an initialization list: