Home > Back-end >  Only one variable is working at a time, and it is dependent on which order I declare them in
Only one variable is working at a time, and it is dependent on which order I declare them in

Time:11-28

I really didn't know what to put as the title for this so ignore that. I also don't know how to describe the question so here is my issue.

#include <iostream>
#include <vector>

class ClassB {
public:
  //LOOK AT THIS PART
  int value;
  char letter;
  ClassB(char t, int v) {
    letter = t;
    value = v;
  }
};

class ClassA {
private:
  ClassB* ptr;
public:
  ClassA(ClassB n) {
    ptr = &n;
  }
  ClassB* getPtr(){
    return ptr;
  }
};

int main() {
  std::vector<ClassA> objects;
  for(int i=0;i<4;i  ) {
    objects.push_back(ClassA(ClassB('a',i)));
  }
  std::cout << "Value: " << objects[1].getPtr()->value << std::endl;
  std::cout << "Letter: " << objects[1].getPtr()->letter;
  return 0;
}

In this code, the output I should receive is

Value: 1
Letter: a

However I am receiving this

Value: 1
Letter

Also, if I were to declare letter before value (look at the comment in code), then the output would say

Value: 0
Letter: ☺

I'm not sure why the order I declare them in would affect anything, or why I'm getting a smiley face instead of a. Any help is appreciated, thank you!

CodePudding user response:

The problem lies here:

 ClassA(ClassB n) {
    ptr = &n;
  }

ClassB is a temporary variable that gets destructed at the end of the function. The pointer becomes invalid and the program goes nuts.

A simple and safe way to go about this, is to use an std::unique_ptr and pass parameters. unique_ptr will automatically delete ClassB when ClassA is deleted:

private:
  std::unique_ptr<ClassB> ptr;
public:
  ClassA(char t, int v) {
    ptr = std::make_unique<ClassB>(t, v);
  }

There's also just keeping a value instead of a pointer.

CodePudding user response:

Do not use a pointer in ClassA for ClassB. Because after the for-loop no object of ClassB exists, anymore. So keep at least a copy of ClassB inside ClassA.

  • Related