Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ passing object to function by refrence, its constructor get called

Tags:

c++

I'm trying to figure out how to use multiple files properly. I made a class in the header file. Then a cpp file that included that header file and implemented everything with Stage::Stage(){} etc. I also made a class called Display that has no default constructor, but requires 2 integer arguments. I made a function in Stage class:

Stage::Stage (Display &display_){
    display = display_;
}

But it causes an error "no matching function for call to 'Display::Display()'" Which is true, it doesn't exist, but it shouldnt need to exist. I'm not trying to create a new Display object here, I'm trying to pass an existing one to the Stage object. (I'm using Dev C++)

like image 221
user3892644 Avatar asked Jun 20 '26 18:06

user3892644


1 Answers

Your Stage constructor must default-initialize display before executing the body of the constructor. All class members must be constructed before executing the body of the class's constructor. No exceptions. The shown code, therefore, attempts to default-construct display before using the assignment operator on it.

Since Display does not have a default constructor, this fails, hence the complaint from your compiler that there is no defualt constructor.

In this situation you must explicitly construct display in the initialization section of the constructor:

Stage::Stage (Display &display_) : display{display_}
{
}

or, pre-C++11:

Stage::Stage (Display &display_) : display(display_)
{
}

This explicitly constructs the display member right from the beginning, presumably using its copy-constructor.

like image 149
Sam Varshavchik Avatar answered Jun 23 '26 11:06

Sam Varshavchik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!