jeudi 17 avril 2014

héritage - C++: comment appeler une fonction de classe parent du dehors - Stack Overflow


I have:


class A{
public:
virtual void foo();
};

class B : public A{
public:
void foo();
};

B *ptr = new B();

I want to call A's foo() DIRECTLY using the 'ptr' pointer.


When I try


(A*)ptr->foo();

it still calls B's version of foo(). How do I call A's version instead?


Is this possible? What are the alternatives? Thank you.




When you name a function with the :: scope-resolution form, you call the named function, as though it were not virtual.


ptr->A::foo();



You need to make your functions public. You do this simply by making the following change:


class A{
public:
virtual void foo();
};

class B : public A{
public:
void foo();
};

When you don't do this, the functions are automatically private and inaccessible from the "outside".



I have:


class A{
public:
virtual void foo();
};

class B : public A{
public:
void foo();
};

B *ptr = new B();

I want to call A's foo() DIRECTLY using the 'ptr' pointer.


When I try


(A*)ptr->foo();

it still calls B's version of foo(). How do I call A's version instead?


Is this possible? What are the alternatives? Thank you.



When you name a function with the :: scope-resolution form, you call the named function, as though it were not virtual.


ptr->A::foo();


You need to make your functions public. You do this simply by making the following change:


class A{
public:
virtual void foo();
};

class B : public A{
public:
void foo();
};

When you don't do this, the functions are automatically private and inaccessible from the "outside".


0 commentaires:

Enregistrer un commentaire