I am not smart
I am not smart

Reputation: 1441

Polymorphism Problem C++

I have these classes:

class A
{
};

class B : public A
{
public:
    B(int val);
private:
    int* m_int;
};

B::B(int val)
{
    m_int = &val;
}

I call the code like so, inside 1 function, i know the vars will be destroyed once they are out of scope, but I only need them in this function:

{
...
int _int = 0;
B obj(_int);
A *obj2 = &obj;
_int++;
...
}

The problem is that _int is changing to 1, but m_int stays the same. I need m_int to reflect what the value in _int is, without the need to update it with code. I thought having a pointer to a memory location would work?

The second problem is that when I hover my mouse over obj2, to see the values of obj, I get the message "children could not be evaluated".

Upvotes: 0

Views: 637

Answers (3)

atoMerz
atoMerz

Reputation: 7672

If you want to change value of _int you should pass it's pointer, they way you're doing now is call by value.

B::B(int* val)
{
    m_int = val; // not ref
}

and m_int should be of type int* not int

For second problem, you're storing a value of derived class in a pointer to base, So when you try to see what's inside obj2 you only see the part of type base, that's why you get message children cannot be evaluated.
Edit--
If you want to see what actually is in obj2, you should cast it to derived type again. And you may not always know that at runtime...

Upvotes: 0

Andreas Brinck
Andreas Brinck

Reputation: 52519

The pointer m_int will stay the same but the value pointed to *m_int will change, you'll also have to pass the value val by reference to the function.

EDIT: Saw your edited question, since this is done from the constructor you can do:

class B : A
{
public:
    B(int& val) : m_int(val) {}
private:
    int& m_int;
};

To have m_int reference the same variable.

Upvotes: 1

sehe
sehe

Reputation: 392833

I'm not too sure whether the following is good advice for a novice, but using a reference like this would work:

class B : A
{
public:
    explicit B(int& val);
private:
    int* m_int;
};

B::B(int& val)
{
    m_int = &val;
}

I'm a bit worried that it is actually a sign of bad design. If it is just for learning purposes, go right ahead, understanding is always important

Upvotes: 3

Related Questions