Constructor Initialization Lists

After reading up on constructor initialization lists from this site
http://www.learncpp.com/cpp-tutorial/101-constructor-initialization-lists/

I tried to the same using strings instead of ints. I however get the error type 'std::basic_string<char>' is not a direct base of 'Person'. I know in C strings are jsut arrays of chars, could that be related to this error?
1
2
3
4
5
6
7
8
9
10
11
class Person{

    private:
        string first_name;
        string last_name;

    public:
        Person(string q = "", string r = ""): first_name(q), string(r){}
        string get_first_name(){return first_name;}
        string get_last_name(){return last_name;}
};
Line 8 will never work:
Person(string q = "", string r = ""): first_name(q), string(r){}
You're passing as a parameter to first_name a variable which doesn't exist in its scope. When you declare q and r they are initialized as local to the Person object scope in that instance. So it has no idea what q and r are yet because it hasn't seen it. Instead try:

1
2
string q2, r2 = "";
Person(string q = "", string r = "") : first_name(q2), last_name(r2){}


This code compiles, but again I've never in my life used this kind of syntax that this guy is providing on the link you provided. I guess it works, but it is ugly.
Last edited on
The only problem with line 8 is that you use string instead of last_name in the initialization list.

1
2
Person(string q = "", string r = ""): first_name(q), string(r){}
                                                     ^
Last edited on
To expand on what Peter87 said, initialiser lists are usually the preferred method for setting the value of variables in the constructor as it is faster and works with consts.
I know in C strings are jsut arrays of chars, could that be related to this error?

But std::string is a bit more than that. And, as you already know, the problem was using the class name where a member variable name was required.

(As you no doubt already realise, shamieh's comment about scope is totally erroneous. Function parameters are visible to the contructor initializer list, or the mechanism would never work!)

initialiser lists are usually the preferred method

Note that the rules changed with C++11 as you can now use "in class initialization", e.g.

1
2
3
4
5
6
class X { 
    int a = 1234; // 1234 is used to init a unless constuctor overload does otherwise
public:
    X() = default;
    X(int z) : a(z) {}
};


But I'm so used to the constructor initialiser list approach I've yet to adopt this approach.

Andy

C++11 allows in-class initialization of non-static and non-const members. What changed?
http://stackoverflow.com/questions/13662441/c11-allows-in-class-initialization-of-non-static-and-non-const-members-what-c
Last edited on
Topic archived. No new replies allowed.