initializing the dynamic array of pointer (in a for loop statement)

Thanks to @nvrmnd, Problem solved!
:-)
Last edited on
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
class Student
{
    Course** C;
    int numberOfCourse;
    // etc..
};

Student::Student( ... )
{
    C = new Course*[ numberOfCourse ];

    for( int i = 0; i < numberOfCourse; ++i )
    {
        C[i] = new Course( /*ctor args*/ );
        // ...
        C[i]->member = var; // access by ->
    }
}

Student::~Student()
{
    for( int i = 0; i < numberOfCourse; ++i )
        delete C[i];
    delete [] C;
}
Last edited on
Thank u @nvrmnd :-)
can u please explain these:
C[i] = new Course( /*ctor args*/ );
// ...
C[i]->member = var; // access by ->
because that's exactly what i need to know, i need to cin (title,grade,name,age) here in this for loop
C[i] = new Course( /*ctor args*/ );

without using new is somewhat equivalent to Course course1( /*arguments*/ ).

If you do not want to supply the arguments and use the default constructor, then just don't include the parentheses.

C[i]->member = var; // access by ->

To access the member, you need to use -> since C[i] is a pointer.

1
2
3
4
5
6
7
    for( int i = 0; i < numberOfCourse; ++i )
    {
        C[i] = new Course;

        cin >> C[i]->title;
        // ...
    }


btw, your Course class won't have a default constructor because you explicitly made one.
You need to add it manually
Last edited on
I'm getting error on this statement C[i] = new Course;
No matching function for call to 'Course::Course()'
and i can't access title because its private
closed account (D80DSL3A)
@Excalibar. Re read nvrmnd last 2 posts. He explained how to deal with both of those problems. If you can't access the private member title, it's because you're not placing that code where shown.
Still not fixed.. please help me guys!!
No matching function for call to 'Course::Course()'
i wrote:
Your Course class won't have a default constructor because you explicitly made one.
You need to add it manually


and i can't access title because its private

Maybe you should use the other constructor, or this method :
void setCourse(string, double, string, int);

( You need some temporary variables like) :
1
2
3
4
5
6
7
8
9
10
11
12
13
// you won't need to add a default constructor to Course

    string title;
    double grade;
    // ...
    for( int i = 0; i < numberOfCourse; ++i )
    {
        cin >> title;
        cin >> grade;
        // ...
        
        C[i] = new Course( title, grade, ... ); // BETTER !
    }


or :
1
2
3
4
5
6
7
8
9
    for( int i = 0; i < numberOfCourse; ++i )
    {
        cin >> title;
        cin >> grade;
        // ...
        
        C[i] = new Course; // ugly
        C[i]->setCourse( title, grade, ... ); // not recommened
    }
Last edited on
Topic archived. No new replies allowed.