Tom
Tom

Reputation: 673

Instance variable in java and c++

as I understood, In java all the variables are refernces.

On the next code:

class Parent { 
    public int x = 12; 
} 
class Child extend Parent { 
public int x = 42; 
} 
Parent p = new Parent(); 
System.out.println(p.x); 
12 
Child c = new Child(); 
System.out.println(c.x); 
42 
p = c; // be careful here! 
System.out.println(p.x); 
12

I think that there is no Slicing here, because we talk about refernces. For that reason, I don't understand why "12" is printed. p is now points to the area of c, and c.x is 42.

The same is happening in the next code on C++:

class Parent { 
  public:
    void example () { cout << "Parent" << endl; } 
}; 
class Child : public Parent { 
  public: 
    void example () { cout << "Child" << endl; } 
};

Parent * p = new Parent(); 
p->example() 
Parent 

Child * c = new Child(); 
c->example() 
Child 

p = c; // be careful here! 
p->example() 
Parent

Upvotes: 1

Views: 305

Answers (5)

Suhail Gupta
Suhail Gupta

Reputation: 23226

In Java you can only hide the field and not override it. For Java

p=c

Now p has the reference of c thus you get answer =12

Upvotes: 0

weekens
weekens

Reputation: 8292

That's because you user p.x, not c.x. The field x is not overriden by Child (as, for example, a method getX() would be). Instead, it is in the subobject, corresponding to a Child class. So, you actually have 2 x: Parent.x and Child.x.

Upvotes: 0

ratchet freak
ratchet freak

Reputation: 48196

for the java side you are declaring 2 separate variables

meaning that for a Child c there's c.x and a ((Parent)c).x that are different variables with their own values

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533520

In Java, you cannot override a field, you can only hide it. Child has two fields Parent.x and Child.x. The reference type determines which field you means by .x

Upvotes: 4

Dark Falcon
Dark Falcon

Reputation: 44181

You are hiding members, not overriding. For the Java example, you cannot override a field. You need to use a function. For the C++ example, your function in Parent must be virtual to be overridden by Child. Otherwise you simply hide the function.

C++:

class Parent { 
  public:
    virtual void example () { cout << "Parent" << endl; } 
}; 
class Child : public Parent { 
  public: 
    void example () { cout << "Child" << endl; } 
};

Upvotes: 7

Related Questions