WorldDominator
WorldDominator

Reputation: 141

C++ Pointers with classes

My programming professor requested that we:

However, I'm a little confused. The "Grade" variable is a class variable, but how do I declare the pointer? Do I declare the pointer as an int?

So I would have something like:

int *ptr;
Grade grade;
ptr = &grade;

Upvotes: 0

Views: 138

Answers (3)

user1810087
user1810087

Reputation: 5334

You declared a pointer to int.
Declaring a pointer to a type is always:

type * ptr;

With that in mind:

Grade grade;
Grade *ptr;
ptr = &grade;
// use
ptr->function();

Upvotes: 0

Baum mit Augen
Baum mit Augen

Reputation: 50111

If you want a pointer to a class T, just write T* foo, just as you would expect. So all in all:

//Declare Pointer and grade Variable:
Grade grade;
Grade* ptr;

//Store variable's address in pointer:
ptr = &grade;

//Call function:
ptr->function();

Upvotes: 0

Joe Z
Joe Z

Reputation: 17956

You're very close. But, you declared a pointer to an integer. That's what int * means. What you want is a pointer to Grade:

Grade* ptr;

The rest of what you wrote looks correct so far.

Once you have ptr = &grade;, you can then call methods in grade by saying ptr->foo() in place of grade.foo(). Both will call the method foo() on the variable grade.

Upvotes: 2

Related Questions