Search code examples
c++inheritanceoverridingvirtual

Why is my virtual function "unique" nor working?


I have two virtual functions in my Base Class, but one of them is not working. I have no idea what's wrong with it. Will anyone please help me?

I've tried changing the virtual method "unique" to a pure virtual method, it throws an error saying "pure virtual function not defined". "Print" seems to work fine, but "unique" is not working.

#include <iostream>
#include "polymor.h"

void print (std::vector<Base *> b)
{
    for (int i = 0; i < b.size(); ++i)
    {
      b[i]->print();
      b[i]->unique();
    }
}

int main()
{
  std::vector< Base * > pointers;
  Base * b1 = new Derived1();
  Base * b2 = new Derived2();
  pointers.push_back(b1);
  pointers.push_back(b2);
  print (pointers);
  return 0;
}

//polymor.h:

#ifndef POLYMOR_H
#define POLYMOR_H

#include <iostream>
class Base
{
public:
  virtual void print()
  {
    std::cout << "Base\n";
  }
  virtual void unique()
  {
    std::cout << "BaseUnique\n";
  };
};

class Derived1: public Base
{
public:
  void print()
  {
    std::cout << "Derived1\n";
  }
  void unqiue()
  {
    std::cout << "Der1Unique\n";
  }
};

class Derived2: public Base
{
  void unqiue()
  {
    std::cout << "Der2Unique\n";
  }
};
#endif```

This is my output:

Derived1
BaseUnique
Base
BaseUnique


Solution

  • You have a typo in your derived class - note that “unique” is spelled incorrectly.

    A great way to diagnose this sort of issue quickly: mark all member functions that are supposed to be overrides with the override modifier. That way, if you make a typo like this, the compiler will flag it as an error rather than resulting in weird runtime issues. For example, this won’t compile:

    void unqiue() override // Nothing named "unqiue" to override 
    {
      std::cout << "Der1Unique\n";
    }