0

I am an amateur in C++. I have a question about the data constructor. Can I initialize the parent class first and then call the constructor of the member class within a member method?

class Data{
    public: 
    Data(datalist);
    setPar();
    getPar();

private:
    //other variables
};

class MainProg{
public:
    MainProg();
    dataInput();
    dataProcess();
    dataOutput:
private:
    Data dataobj;
};

MainProg::dataInput(parlist){
    ..... //read data here
    dataobj(datalist);
}
bolov
  • 72,283
  • 15
  • 145
  • 224
YS_Jin
  • 55
  • 4
  • 2
    [Calling a constructor to re-initialize object](https://stackoverflow.com/q/2166099) – 001 Jun 17 '22 at 20:57
  • 2
    please don't show us pseudocode that looks like C++. Creat a [mre] of what you want. – bolov Jun 17 '22 at 20:57
  • 2
    Note: all class members are initialized before the program enters the body of the constructor, so `MainProg`'s constructor must initialize `dataobj` and must supply a valid `datalist` in order to initialize `dataobj`. You'll have to rethink how you intend to approach this problem. – user4581301 Jun 17 '22 at 21:01
  • 2
    Note: C++ doesn't reward guesswork very often and is too complicated to be learned via Stack Overflow questions. If you have not already, I strongly recommend getting and reading [a good introductory book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – user4581301 Jun 17 '22 at 21:03

1 Answers1

1

You can call the destructor and then the constructor

dataobject.~Data();
dataobject(datalist);

but you really really shouldn't.

Why can't you assign to dataobject?

dataobject = Data(datalist);

Or initialize in the constructor directly:

MainProg::MainProg(something parlist) : dataobject(read_data(parlist)) { }
static Data read_data(something parlist) { ... }

Or write a factory:

MainProg from_parlist(something parlist) {
    // read data here
    return MainProg(datalist);
}

or simply read the data in main before you create MainProg.

Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42