Basic Inheritance Question

I have a class Duck that extends Animal..can anyone tell me why the line near the bottom ( see the comments) gives the following error:
ISO C++ forbids initialization of member `noise'



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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <string>

using namespace std;


class Animal{

public:
    Animal(){
    animalNoise = "-";
    myId= ++nextId;
    name = "";
    }

    Animal(string s){
    animalNoise="-";
    name = s;
    myId = ++nextId;
    }

    int getId(){
    return myId;
    }

    void makeNoise(){
        cout << animalNoise;
        }

    string getName(){
    return name;
    }
    string getAnimalNoise(){return animalNoise;}

private:
        int myId;
        static int nextId;
        string name;

protected:
        string animalNoise;
};


int Animal::nextId=0;


class Duck: public Animal{
    public:
        Duck(){
            animalNoise= noise;
        }

private:
//THE NEXT LINE CAUSES THE ERROR
 string noise= "Quack Quack";

};

Last edited on
You cannot directly initialize a data member within a class. It must be initialized via constructor or setter function.
1
2
3
4
5
6
7
8
9
public:
   Duck() {
       animalNoise = noise();
   }

private:
   static string noise() 
        { return "Quack"; }
};


but this seems rather pointless.

First, I'd make a constructor on Animal that takes a noise and name as parameters, then I'd:

 
Duck( const std::string& name ) : Animal( name, "Quack" ) {}

thanks!
Topic archived. No new replies allowed.