1

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?

2
  • 2
    Parent* c passes a Parent by reference (specifically by a pointer), but the pointer itself is passed by value. c is 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). Commented Mar 5, 2020 at 16:29
  • Pass a Parent** p to setChild and assign the result of new Child1(); to *p. Commented Mar 5, 2020 at 16:30

1 Answer 1

2

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Sometimes I hate C++. Defeated by an &. I'll accept your answer as soon as it allows me. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.