1

I am trying to create an instance of class inside class. I have declared two classes = first

class Student{
public:
    Student(string m,int g){
        name=m;
        age=g;
    }
    string getName(){
        return name;
    }
    int getAge(){
        return age;
    }
private:
    string name;
    int age;

};

And second , where i want to create instance of student.

class Class{
public:

    Class(string n){
        name = n;
    };
    string studentName(){
        return Martin.getName();
    }
private:
    string name;
    Student Martin("Martin",10);
    Student Roxy("Roxy",15);

    };

I keep getting this errors

'((Class*)this)->Class::Martin' does not have class type

expected identifier before string constant|

The Student was defned before Class so it shouldnt have problem to access it. What causes this behavior? How can i fix it?

1 Answer 1

4

Member initialization should be done in your constructors initialization list:

Class(string n)
     : Martin("Martin",10)
     , Roxy("Roxy",15)
{ 
    name = n;
};

private:
   string name;
   Student Martin;
   Student Roxy;

Some more information on member initialization can be found here: http://en.cppreference.com/w/cpp/language/initializer_list

And a more tutorial like explanation might also be useful to you: http://www.learncpp.com/cpp-tutorial/8-5a-constructor-member-initializer-lists/

As James Root pointed out in the comments instead of:

private:
  string name;
  Student Martin("Martin",10);
  Student Roxy("Roxy",15);

you can write

private:
  string name;
  Student Martin{"Martin",10};
  Student Roxy{"Roxy",15};

But make sure you compile your code with the c++11 standard. On older compilers you might need to add -std=c++11 to your compile command like: g++ -o foo -std=c++11 main.cpp

Sign up to request clarification or add additional context in comments.

2 Comments

In-class initialization is perfectly acceptable, but needs to use braces instead of parenthesis.
You are absolutely correct for the c++11, but you need to compile it with the -std=c++11 flag (at least for older compilers)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.