Can public members of base class be initialised using initialisation list in a derived class.

Hi Guys :)
I am trying to initialize a public data member of a base class (Animal class in my example) from a derived class (Cat class in my example) using initialization list as I have read that "all the public members of base class are inherited by the derived class". Then

1) why the initialization using initialization list in derived class fails if the data member is inherited by the derived class.

2) Why the same passes when we use assignment instead of initialization list.


Here is the error producing code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

#include <iostream>

class Animal
{
    public:
        //Animal(unsigned int p_nLegs);
        unsigned int nLegs;
        unsigned int getLegs();
        virtual void speak() = 0;
};

unsigned int Animal::getLegs()
{
    return nLegs;
}


class Cat : public Animal
{
    public:
        Cat(unsigned int p_nLegs);
        virtual void speak();
};


Cat::Cat(unsigned int p_nLegs) : nLegs(p_nLegs) {}

void Cat::speak()
{
    std::cout << "\n I am a cat \n";
    return;
}



This compiles without error

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

#include <iostream>

class Animal
{
    public:
        //Animal(unsigned int p_nLegs);
        unsigned int nLegs;
        unsigned int getLegs();
        virtual void speak() = 0;
};

unsigned int Animal::getLegs()
{
    return nLegs;
}


class Cat : public Animal
{
    public:
        Cat(unsigned int p_nLegs);
        virtual void speak();
};


Cat::Cat(unsigned int p_nLegs) /*: nLegs(p_nLegs)*/ { nLegs = p_nLegs;}

void Cat::speak()
{
    std::cout << "\n I am a cat \n";
    return;
}


Thanks :)
member initializer list elements are direct bases and members. See for example http://en.cppreference.com/w/cpp/language/initializer_list

To make your code work properly, you'd have to uncomment Animal(unsigned int p_nLegs); and use Cat::Cat(unsigned int p_nLegs) : Animal(p_nLegs) {}
Last edited on
> all the public members of base class are inherited by the derived class
they may be inaccesible or even invisible, put they are inherited.


Also, let the base class handle itself.
Topic archived. No new replies allowed.