jyim
jyim

Reputation: 119

Destructors and constructors

Would someone please explain to me why I get an "Error: not declared in this scope?"

num and denom are private members of class Rationalnumber.

Thanks!

Rationalnumber::Rationalnumber(){
num = 0;
denom = 1;
int * n = new int;
int * d = new int;
*n = num;
*d = denom;
}

Rationalnumber::~Rationalnumber(){
delete n;
}

Upvotes: 0

Views: 99

Answers (4)

emartel
emartel

Reputation: 7773

You define n in the scope of your constructor. This code is so simple that you shouldn't even new and delete ints. Just store n and d as class members. Your code, even fixed, would leak d as you new it but don't delete it.

Upvotes: 0

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361264

Rationalnumber::~Rationalnumber(){
delete n;
}

Is n a member of the class? If not, then it will give error, as n is neither declared in the destructor, nor is it a member of the class.

You've declared n in the constructor however, but that is local to the constructor only.The destructor (or any other function) cannot access that variable (which is declared in another function or constructor).

Upvotes: 1

Rook
Rook

Reputation: 6145

n is a local variable in the class constructor. When it goes out of scope when the constructor completes, it is no longer visible to any other part of your application; that memory has been leaked.

There's no local or member variable called n at the point at which the destructor is called, hence: not declared in this scope.

Upvotes: 3

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27632

"n" is a local variable in the constructor.

You probably want it to be a member variable in the class:

class Rationalnumber {
    int* n;
    int* d;
    .........
};

Upvotes: 2

Related Questions