0

Is it possible to access a base class function which has the same signature as that of a derived class function using a derived class object?. here's a sample of what I'm stating below..

class base1 {
public:
    void test()
    {cout<<"base1"<<endl;};
};

class der1 : public base1 {
public:
    void test()
    {cout<<"der1"<<endl;};
};

int main() {
der1 obj;
obj.test(); // How can I access the base class 'test()' here??
return 0;
}

3 Answers3

6

You need to fully qualify the method name as it conflicts with the inherited one.

Use obj.base1::test()

Arkaitz Jimenez
  • 22,500
  • 11
  • 75
  • 105
  • 3
    The formal term is "overrides", since the signatures match. Otherwise you'd say the derived "hides" the base class method. In either case, there is no "inherited method name" anymore. – MSalters Aug 19 '09 at 09:34
  • 1
    I doubt whether the correct term is 'override' or 'hides'. In the C++ standard 'override' is only used with virtual functions and in 10.2 Member name lookup, the standard says: 'A member name f in one sub-object B hides a member name f in a sub-object A if A is a base class sub-object of B.' – David Rodríguez - dribeas Aug 19 '09 at 10:30
  • @MSalters: This is definitely not "overriding". That is only for virtual functions. – Richard Corden Aug 19 '09 at 11:44
1

You can't override a method in derived class if you didn't provide a virtual key word.

class base1
{
    public:
        void test()
        {
            cout << "base1" << endl;
        };
};

class der1 : public base1
{
    public:
        void test()
        {
            cout << "der1" << endl;
        };
};

int main()
{
    der1 obj;
    obj.test(); // How can I access the base class 'test()' here??
    return 0;
}

So the above code is wrong. You have to give:

virtual void test();

in your base class

Samuel Harmer
  • 4,264
  • 5
  • 33
  • 67
shafeer
  • 11
  • 1
  • 1
    @Styne666 Please do not be rude in your "edit summary". That's visible to everyone. Read the [faq](http://stackoverflow.com/faq#etiquette) - "*Civility is required at all times; rudeness will not be tolerated*" – Josh Darnell Mar 22 '12 at 14:36
0

You can use this:

((base)obj).test();
DarkAjax
  • 15,955
  • 11
  • 53
  • 65