user2510141 user2510141 - 10 months ago 47
C++ Question

C++ Template Array class: Error generation depends on whether it inherits an interface or not

Sorry for the vague title - I didn't know how to shortly describe my question. I have been playing around with the composite design pattern and ran into the following situation. Say I have an interface

class interface
{
public:
virtual ~interface() { }
virtual void methodA(const uint8_t* ptr) = 0;
};


And say I have a template class that adheres to this interface (this is just a simple example I know it doesn't make much sense).

template <typename T>
class customArray
{
public:
void methodA(const uint8_t* ptr)
{
if (m_data.size())
m_data[0].methodA(ptr);
}

int methodB(uint8_t* ptr)
{
if (m_data.size())
return m_data[0].methodB(ptr);

return 0;
}

void push_back(const T& elm)
{
m_data.push_back(elm);
}

private:
std::vector<T> m_data;
};


Note that the template class does not inherit the interface. Now if I define some simple class

class customPrimitive
{
public:
int methodB(uint8_t* ptr)
{
(void)ptr;
return -1337;
}
};


And use it like so

customArray<customPrimitive> arr;
arr.push_back(customPrimitive());
printf("Got %i\n", arr.methodB(NULL)); // Prints -1337
// arr.methodA(NULL); This will make build fail


Obviously the build should fail if I try to call methodA. But why doesn't it fail when I avoid calling it ?

Furthermore, why does the build fail if I make the array inherit the interface ? In this case it happens regardless of whether I call the method or not.

If anyone could provide me with some insight that would much appreciated.

Thanks,

Answer Source

Because you're not calling it, the compiler is optimizing customArray.methodA away.