2

Both of my classes: Parent and Child are the same (for now) and have the same constructor.

class Parent{
protected:
  string name;
public:
  Parent(string &n, vector <int> &v) {
  /* read n and v into vars */
};

class Child : public Parent {
public:
  Child(string &n, vector <int> &v) : Parent(n, v) {}
};
vector <int> val;
string nam, numb;
if(val[0] == 0) 
  Child* ptr = new Child(nam, val);
else
  Parent* ptr = new Parent(nam, val);

myMap.insert(Maptype::value_type(numb, ptr) );

Is it legal to pass Child* ptr object as Parent* ptr object? I've heard that they have the same pointer type, so it should be alright. Then why am I getting warning: unused variable 'ptr' warning: unused variable 'ptr' error: 'ptr' was not declared in this scope ? My program works fine with Parent class only. I feel like I haven't inherited Parent right.

Mat
  • 188,820
  • 38
  • 367
  • 383
user1078719
  • 195
  • 2
  • 3
  • 15
  • "parent/child" is not a good metaphor of the C++ object model and in particular of public inheritance. "Base" and "Derived" are much better. A child *is* not a parent, but derived classes *are* in a sense a version of their public bases. – Kerrek SB Jun 10 '12 at 13:51

2 Answers2

6

The code creates two separate variables called ptr, both with very limited scope.

Consider the following:

if(val[0] == 0) 
  Child* ptr = new Child(nam, val);
else
  Parent* ptr = new Parent(nam, val);

It is equivalent to:

if(val[0] == 0) {
  Child* ptr = new Child(nam, val);
} else {
  Parent* ptr = new Parent(nam, val);
}
// neither of the `ptr' variables is in scope here

Here is one way to fix your code:

Parent* ptr;
if(val[0] == 0) 
  ptr = new Child(nam, val);
else
  ptr = new Parent(nam, val);

Once you do this, you also need to make sure that Parent has a virtual destructor. See When to use virtual destructors?

Community
  • 1
  • 1
NPE
  • 438,426
  • 93
  • 887
  • 970
  • Thank you. It's still kinda mysterious for me why those pointer have the same type. – user1078719 Jun 10 '12 at 08:30
  • 1
    @user1078719: Actually, they don't. It is, however, the case that `Child*` can be converted to `Parent*`. http://www.parashift.com/c++-faq-lite/basics-of-inheritance.html#faq-19.4 – NPE Jun 10 '12 at 08:32
-1

because you declare the ptr in the if statement only, try declaring it just above the if statement so it could be like aix answer

justcoder
  • 56
  • 4