简体   繁体   中英

For a class with parameterized constructor, create an object without passing arguments

I know that we can't do what the title says. But why does the below code work just fine & print Value of G in class RT: 2 even though object of class RT is created without passing arguments in the line RT initial_rt;

#include <iostream>
class RT {
    public:
        RT(int var1): G(var1) {std::cout << "Value of G in class RT: "<< G << std::endl;}
    private:
        int G; 
};

class class2 {
    public:
        RT initial_rt;
        class2(RT G) : initial_rt(G) {}
};

int main()
{
    int G=2;
    class2 *cls2_obj = new class2(G);
    return 0;
}

What am I missing?

Thanks!

This line:

RT initial_rt;

is just a declaration .

This line:

class2(RT G) : initial_rt(G) {}

is the ctor and its implementation .

The part after the colon is called initialization list , and this is where the initial_rt member is being initialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM