Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- class Foo {
- public:
- int bar;
- Foo(int num): bar(num) {};
- };
- int main(void) {
- std::cout << Foo(42).bar << std::endl;
- return 0;
- }
- Foo(int num): bar(num)
- Foo(int num): bar(num) {};
- Foo(int num)
- {
- bar = num;
- }
- Cost of Member Initialization = Object Construction
- Cost of Member Assignment = Object Construction + Assignment
- Foo(int num) : bar() {bar = num;}
- Foo(int num): bar(num){}
- class MyClass
- {
- public:
- //Reference member, has to be Initialized in Member Initializer List
- int &i;
- int b;
- //Non static const member, must be Initialized in Member Initializer List
- const int k;
- //Constructor’s parameter name b is same as class data member
- //Other way is to use this->b to refer to data member
- MyClass(int a, int b, int c):i(a),b(b),k(c)
- {
- //Without Member Initializer
- //this->b = b;
- }
- };
- class MyClass2:public MyClass
- {
- public:
- int p;
- int q;
- MyClass2(int x,int y,int z,int l,int m):MyClass(x,y,z),p(l),q(m)
- {
- }
- };
- int main()
- {
- int x = 10;
- int y = 20;
- int z = 30;
- MyClass obj(x,y,z);
- int l = 40;
- int m = 50;
- MyClass2 obj2(x,y,z,l,m);
- return 0;
- }
- // Example 1
- Foo(Bar b)
- {
- bar = b;
- }
- // Example 2
- Foo(Bar b)
- : bar(b)
- {
- }
- Bar bar(); // default constructor
- bar = b; // assignment
- Bar bar(b) // copy constructor
- class Foo {
- public:
- string str;
- Foo(string &p)
- {
- str = p;
- };
- };
- class Foo {
- public:
- string str;
- Foo(string &p): str(p) {};
- };
- string();
- string& operator=( const string& s );
- string( const string& s );
- Foo(int num): bar{num} {}
Add Comment
Please, Sign In to add comment