Question: constructor in constructor question (heap vs stack)

Hi guys,

I have a questions that's been bothering me for some time. Here's the scenario...

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
class Record{
public:
 Record():number(0){}
 Record(int num):number(num){}

 void init(int num){number=num;}
 int number;
};

class Student{
public:
 Student(){
   ptr_rec=new Record(10);//allowed
   rec.init(10);//allowed
   Record rec(10);//allowed but a difference object, therefore no good
   rec(10);//not allowed
 }
 ~Student(){
	delete ptr_rec;
 }
 void viewStudent(){
	std::cout<<rec.number<<std::endl;
 }
private:
 Record rec;
 Record *ptr_rec;
 
};


My question is: without going to the heap, or using an init() function, is it possible to initialize a constructor with arguments, in another constructor? And if not why not.

Thanks,

Mike
Yes; use the initializer list. In your case:
1
2
3
4
5
class Student {
public:
    Student() : rec(10) {
    }
    // ... 

http://www.cplusplus.com/doc/tutorial/classes/#member_initialization
Members are initialized before the opening brace, so

1
2
3
4
Student() : rec(10),
            ptr_rec(new Record(10))
{
}
Last edited on
Thanks guys, that anwsered my question
Topic archived. No new replies allowed.