Pass parameters to the constructor of a class that is a member of another class
source link: https://www.codesd.com/item/pass-parameters-to-the-constructor-of-a-class-that-is-a-member-of-another-class.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Pass parameters to the constructor of a class that is a member of another class
I have class called Bar, and in this class Bar there is an object of type Foo (a class). Class Bar takes 3 parameters, x, y and z. Foo takes 2 parameters, y and z.
currently I'm doing this:
class Bar {
public:
Bar(int x, int y, int z) {
foo = new Foo(y, z);
do something with x;
}
private:
Foo * foo;
};
I remember seeing in a book another way to do this using a colon but I don't remember how exactly.
What is the standard or usual way of doing something like this?
Use an initializer list and avoid dynamic allocation:
class Bar {
public:
Bar(int x, int y, int z) : foo(y, z) {}
private:
Foo foo;
};
Related Articles
How do I pass parameters to the second-level top class
use the constructor parameterized in the constructor of other classes
TestNG - pass parameters to the constructor where the parameters are decided according to the test name
How does the concept of a class change when passing data to the constructor instead of the method's parameters?
Providing passing arguments to the constructor in different public classes
Call the class method using Reflection with different parameters in the constructor?
Laravel how to pass parameters to the controller's middleware
How to pass parameters to the REST resource using Jersey 2.5
Best way to write the constructor of a class that holds an STL container in C ++ 11
Need help understanding the parameters of the constructor and the static variables
How to pass parameters from the nice URL to JSP pages?
Why is the constructor of a class that implements the Runnable interface not called?
Python bottle: how to pass parameters in the function handler
Pass parameters in the URL (not with php GET)
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK