Reputation: 37
I'm new at learning c++ and a have stuck in constructors.I have a class Teacher
and a Class Subject
. In class Teacher
a have an object Subject S[]
. How I can initialize with constructor from class Teacher
the S[]
? I have tried this:
in Teacher.h file
class Teacher
{
private:
string name;
Subject *S[20];
public:
Teacher();
}
in Teacher.cpp file
Teacher::Teacher()
{
name=" ";
for(int i=0; i<20; i++)
{
S[i].Subject();
}
}
in Subject.cpp file the Constructor is:
Subject::Subject()
{
day=0;
hour=0;
for(int i=0; i<10; i++)
{
classroom[i]=" ";
}
}
Upvotes: 0
Views: 91
Reputation: 238461
In class Teacher a have an object Subject S[]
No you dont:
Subject *S[20];
Teacher::S
is an array of pointers.
S[i].Subject();
.
is used for member access. Pointers do not have members, so this is syntactically wrong. Besides, you never call a constructor directly. It is called automatically as a consequence of initializing a variable, or a new expression.
It seems that to want to have an array of Subject
objects as a member instead. This is how you would declare such member:
Subject S[20];
The objects in the array will be constructed before the body of Teacher
constructor is executed.
Upvotes: 1
Reputation: 234875
The way you currently have it, you'd have to write
S[i] = new Subject();
rather than
S[i].Subject();
But that burdens you with having to remember to call delete
at some point. It would be far better to use
std::list<Subject> S;
in place of
Subject *S[20];
and then push_back
or even the flashier emplace_back
in place of S[i].Subject();
See http://en.cppreference.com/w/cpp/container/list
Upvotes: 1