Joseph D
Joseph D

Reputation: 115

Syntax error, cant use struct in c++ class

I am currently learning C++ and working on a assignment which asks me to create:

Class student (must be separated by .h and .cpp) that inherits class person that has:
a. Attributes: dynamic array of struct holding courses and their grades and other attributes
b. Member functions: display the grade of a given course and other member functions as as needed

So, to start, I have already created the class person; so don't worry about the inheritance nor classes, my only problem is with structs, here is my code:

student.h

#include <string>
#ifndef student_h
#define student_h
#include "person.h"
class student: public person {

private:
        struct stud {
            int age;
        };

public:
        student();
        int getAge();
};

#endif

student.cpp

#include <iostream>
#include <string>
using namespace std;
#include "student.h"


student::student() {


}

int student::getAge() {

    return stud.age;
}

So, my logic is, in the same way, that if you define a private integer in the .h file and use it freely in the .cpp file, I should do it for the struct. When I try to compile student.cpp for synthax error before running main.cpp, I get this error:

.\student.cpp(14) : error C2275: 'student::stud' : illegal use of this type as an expression

which is referring to return stud.age;. I am using (and forced to use) Visual Studio 2005.

How do I retrieve the age of the struct using a function? Also, what does my teacher mean by an array of structs? Does it mean I have to create the array in the main and how?

Upvotes: 1

Views: 1622

Answers (2)

Reuben Thomas
Reuben Thomas

Reputation: 52

If you really want to store stuff in an internal struct (I don't think you should) then you could write your struct like this:

struct {
    int age;
} stud;

In your example, you're declaring a struct of type stud but then not creating an instance. In the snippet above, I declare an anonymous struct (ie it's type has no name) and then create an instance called stud. Your current getAge should work if you make this change.

'dynamic array' == vector

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Nested class stud defines a new type, not a variable of that type. If you wish to make a variable of type stud, declare a separate member for it, like this:

class student: public person {
private:
        struct stud_t {
            int age;
        };
        stud_t stud;
public:
        student();
        int getAge();
};

Now stud_t is the name of the type, and stud is the name of a variable of that type.

Alternatively, you could make stud an anonymous struct, like this:

class student: public person {
private:
        struct {
            int age;
        } stud;
public:
        student();
        int getAge();
};

Upvotes: 3

Related Questions