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?
There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.
A constructor is used to initialize the state of an object. A method is used to expose the behavior of an object. A constructor must not have a return type.
A copy constructor is a member function that initializes an object using another object of the same class.
This instance can be created in another class using the new keyword. The new keyword is a very powerful keyword in Java which allows for instantiation of another class. This is how you create an object of a class in another class without using inheritance.
In constructor of Circle you are trying to create an instance of Box, which is too late because by the time the body of constructor will be executed, the members of Circle shall be constructed already. Class Box either needs a default constructor or you need to initialize box in an initialization list:
Box constructBoxFromStr(const std::string& str) {
int i;
...
return Box(i);
}
class Circle
{
private:
int area;
Box box;
public:
Circle(int area, string str)
: area(area), box(constructBoxFromStr(str)) { }
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With