ObscurityGamer
ObscurityGamer

Reputation: 35

C++ Class Inheritance Segmentation Fault

I'm doing a thing with C++ where I'm making an object of abstract class Parent and initializing it in a function to a child class. When I initialize the object when it's created, everything works wonders. When I initialize it in a function, I get a segmentation fault.

Here's a code outline of what I'm doing

_class.h

#ifndef CLASS_H_INCLUDED
#define CLASS_H_INCLUDED

class Parent{
  public:
    virtual void foo() = 0;
};

class Child1 : public Parent{
  public:
    virtual void foo(){
      ...
    }
};

class Child2 : public Parent{
  public:
    virtual void foo(){
      ...
    }
};

#endif

main.cpp

#include <iostream>

using namespace std;

#include "main.h"
#include "_class.h"

void setChild(Parent* c){
  c = new Child1();
}

int main() {
  Parent* c;// = new Child1();

  setChild(c);

  c->foo(); //Seg Fault
}

Obviously I could just initialize in main, but I'd rather initialize in the function. Is this possible, and if so, what am I doing wrong?

Upvotes: 1

Views: 576

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

You're setting the local c in setChild to a new object, but the one in main is not changed. There are two ways to change the value in the caller.

One is to pass the parameter by reference:

void setChild(Parent*& c)

the other is to return it, rather than use a parameter

Parent *setChild() {
    return new Child1();
}

Upvotes: 2

Related Questions