C++ Abstract class pointer in method

  abstract-class, c++, initialization

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!

Source: Windows Questions C++

LEAVE A COMMENT