Reputation: 9
I want to access constructors member initializes as many required. When class object is initialized by program, the default constructor will be called. so at same time, the constructor call constructor initialize what I mentioned.
class A {
public:
A();
void fun1();
void fun2();
};
A::A()
: fun1()
, fun2()
{
cout << " Hi" << endl;
}
void A::fun1()
{
cout << "Hello" << endl;
}
void A::fun2()
{
cout << "Bye" << endl;
}
int main()
{
A obj_a;
return 0;
}
Expected result:
Hi, Hello, Bye
Error message
error: class ‘A’ does not have any field named ‘fun1’
A::A():fun1(), fun2() {
Upvotes: 0
Views: 2691
Reputation: 657
You are calling functions in initializer list, you supposed to initialize data members there. Compiler looks for data member called fun1 and fun2 and cant find any, so you are informed about. Yo can try like this below:
class A {
public:
A();
void fun1();
void fun2();
};
A::A() {
cout << " Hi" << endl;
fun1();
fun2();
}
void A::fun1() {
cout << "Hello" << endl;
}
void A::fun2() {
cout << "Bye" << endl;
}
int main() {
A obj_a;
return 0;
}
Upvotes: 1
Reputation: 490
You are getting the error:
error: class ‘A’ does not have any field named ‘fun1’
A::A():fun1(), fun2() {
Because class A
does not have any data member with name fun1 or fun2.
Member Initialization List is used to initialize data members or invoking base constructors.
Please see for details: Constructor & Member Initilization List
Methods of the class can be called within constructor body like:
A::A()
{
fun1();
fun2();
}
Upvotes: 0