Search code examples
c++initializationpolymorphismabstract-classpass-by-reference

C++ Abstract class pointer in method


So I have a c++ project that I'm working on and I'm trying to understand an other guys code but all I get are errors and confusion about c++ abstract classes.

So What I have is a header file a cpp file and a main program.

I want to create an abstract class pointer and then pass it to a method that initializes it to a subclass and then back in the main program I can use it as the subclass:

main.cpp:

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

using namespace std;

void parse(A* a){
  a = new B();
  a->foo();
}

int main() {
  A* a;
  parse(a);
  a->foo();
}

a.h:

class A{
  public:
    virtual void foo() const = 0;
    virtual ~A(){ }
};

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

class C : public A{
  public:
    void foo() const override;
};

a.cpp

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

void B::foo() const{
  std::cout << "B" << std::endl;
}

void C::foo() const{
  std::cout << "C" << std::endl;
}

Basically here I think I should cee a B but I get a segmentation error or the program exits without printing anything.

Thank you for your help!


Solution

  • In main you have uninitialized pointer a

    int main() {
      A* a;
      parse(a);
      a->foo();
    }
    

    So this statement

      a->foo();
    

    results in undefined behavior.

    As for the function parse

    void parse(A* a){
      a = new B();
      a->foo();
    }
    

    then it deals with its local variable a. Changing the local variable does not affect the original pointer declared in main.

    You need to declare the parameter as having a referenced type

    void parse(A* &a){
      a = new B();
      a->foo();
    }
    

    In this case the pointer a declared in main will be passed to the function by reference and the function will change the original pointer a.