user3706129
user3706129

Reputation: 229

Creating instance of class inside class

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?

Upvotes: 1

Views: 3944

Answers (1)

Goldfishslayer
Goldfishslayer

Reputation: 450

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

Upvotes: 4

Related Questions