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?
Parent* cpasses a Parent by reference (specifically by a pointer), but the pointer itself is passed by value.cis a copy of the caller's argument and changes made to the copy are not duplicated at the caller. Use a reference :void setChild(Parent* & c).Parent** ptosetChildand assign the result ofnew Child1();to*p.