derived members & initializer list

A

Aman

Hi,
Why does the member initialization list not work for derived members
but the assignment within the constructor works fine ?
ex ->
class X{
protected :
short int i ;`
};
class Y: public X{
public :
Y() ;
} ;
Y::Y() : i(10) {} // this gives compilation error
Y::Y() { i = 10 ;} // this works fine .

why is that ?


regards,
Aman .
 
W

White Wolf

Aman said:
Hi,
Why does the member initialization list not work for derived members
but the assignment within the constructor works fine ?
ex ->
class X{
protected :
short int i ;`
};
class Y: public X{
public :
Y() ;
} ;
Y::Y() : i(10) {} // this gives compilation error
Y::Y() { i = 10 ;} // this works fine .

why is that ?

Because those members are initialized by the constructor of the base, you
cannot initialize them again. Only assign.
 
R

Ron Natalie

Aman said:
Y::Y() : i(10) {} // this gives compilation error

You can only initialize members and your direct base classes.
i is neither, it's a member of your base class.
Y::Y() { i = 10 ;} // this works fine .

This is assignment. i is an accessible base class member and hence
the access is fine.
 
A

Agent Mulder

Hi,
Why does the member initialization list not work for derived members
but the assignment within the constructor works fine ?
ex ->
class X{
protected :
short int i ;`
};
class Y: public X{
public :
Y() ;
} ;
Y::Y() : i(10) {} // this gives compilation error
Y::Y() { i = 10 ;} // this works fine .

why is that ?
</>


class X{
public :
X(int a):i(a){}
protected :
int i;
};
class Y: public X{
public :
Y() ;
} ;
Y::Y() : X(10) {} // fill X::i in initializer of Y through constructor of X


-X
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top