简体   繁体   中英

Function signature and inheritance in C++

Assume I have two classes A and B and B derives A .

Class A:

class A
{
public:
    virtual const unsigned char* getArray()
    {
        return array;
    }

protected:
    unsigned char array[250];
};

Class B:

class B : public A
{
public:
    virtual unsigned char* getArray()
    {
        return array;
    }
};

Can I create a class C that will do this?

class C
{
public:
    const unsigned char* getArrayMiddle(A &a)
    {
        return (a.getArray() + 125);
    }

    unsigned char* getArrayMiddle(B &b)
    {
        return (b.getArray() + 125);
    }
};

With this simple example, I am trying to know if I can create two methods in the class C , one of them returning a const pointer if required by the type of the object it receives.

Will the compiler automatically call the right method in C depending on the type of the parameter, even if B derives A ?

To clarify, if I have

A* obj = new B();
C c;
c.getArrayMiddle(*obj);

which function will be called? Could it create unexpected situations?

Will the compiler automatically call the right method in C depending on the type of the parameter, even if B derives A ?

The compiler will interpret a method call as being to either of the two methods depending on the static (compile-time) type of argument expression. Whether you consider this to be the right method is determined, I suppose, by which one you want to be called.

If the static type of the argument is B & then the second variant (returning unsigned char * ) will be called. If it is not a B & but is an A & then the first variant (returning const unsigned char * ) will be called.

The precise rules determining which overloaded method is called in which circumstances are quite complex, but in general, a more specific suitable candidate is usually preferred. In this case B & is more specific than A & , so it will be called if indeed the argument is a B & , even though it is in that case trivially convertible to an A & due to the inheritance hierarchy.

However , it is worth noting that (as per comment from cpplearner) your code as posted should not compile. B should not be able to override getArray with a version which drops the const qualifier. G++ 5.4 diagnoses this as an error. You could instead not have one method override the other: drop the virtual specifier, or give them different names, or mark the method in A as a const method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM