Constructor
Return type: None
Cannot access to address of ctr
Inheriting ctr: Cannot
PRIVATE SCOPED CTR*: Can ctr be inside private section(Yes. Single DP)
Ctr calling Hierarchy (Base Class > Derv Class Ctr)
-
Derived class object also have inherited properties of Base class,
and only base class constructor can properly initialize base class members
class A{
public:
A() { cout<<"base ctr"; }
~A() { cout<<"base dtr"; }
};
class B: public A {
public:
B() { cout<<"Derv ctr"; }
~B() { cout<<"Derv dtr"; }
};
int main(){
B obj;
}
$ a.out
base ctr
Derv ctr
Derv dtr
Base dtr
Base class constructor should be defined
class A{
public:
A();
~A();
};
class B: public A {
public:
B() { cout<<"B ctr"; }
~B() { cout<<"~B"; }
};
int main(){
B obj;
}
# ./a.out
Error cannot find A::A()
Ctr Initializer list
In the initializer list, the order of execution takes place according to the order of declaration of member variables.
class test{
int a; //Declared 1st
int b; //Declared 2nd
public:
test (int x): b(x), a(b * 2) {
cout << b << a; //b=10, a=garbage
}
};
int main() {
test obj(10);
return 0;
}
$ ./a.exe
b = 10
a = garbage value
This is because, a is declared before b. Initialization of a will happen before b.
Since a = b*2, and b does not have value hence a is initialized to garbage.
class A{
public:
A();
~A();
};
class B: public A {
public:
B() { cout<<"B ctr"; }
~B() { cout<<"~B"; }
};
int main(){
B obj;
}
# ./a.out
Error cannot find A::A()
class test{
int a; //Declared 1st
int b; //Declared 2nd
public:
test (int x): b(x), a(b * 2) {
cout << b << a; //b=10, a=garbage
}
};
int main() {
test obj(10);
return 0;
}
$ ./a.exe
b = 10
a = garbage value
This is because, a is declared before b. Initialization of a will happen before b.
Since a = b*2, and b does not have value hence a is initialized to garbage.