#referencing object created in constructor c++?
60 messages · Page 1 of 1 (latest)
you do know that variable is an instance variable, right?
which means that each instance of class A will have its own numObj variable
I moved numObj to my A.h header file and made it extern. However, when I run my main.exe, none of my print statements output anymore
show code
A.h:
`
#pragma once
class A: public B{
A(int a);
}
extern vector<A> numObj
A.cpp:
vector<A> numObj;
A::A(int b): B(b){
numObj.push(back(A(b));
}
`
it would probably be better to just do numObj.push_back(*this);
does your program ever halt?
yes, whenever I run my .exe file, nothing is printed out
when before I added this class, the print statements worked just fine
im asking because your constructor calls itself, so it's an infinite loop
#include "<A.h>" int main(){ cout << "test"'; A test(3); cout << "test 2"; }
"test" is printed but not "test 2"
answer me this
yes the code does terminate
you can do code block with triple backticks btw
Oh
that doesn't make sense
because of this
Ill show my B.cpp code maybe thats the issue
it absolutely isn't
B.cpp:
#include "A.h"
vector<A> numObj;
B(int b){
numObj.push_back(A(b));
}
well, unless the constructor for B exits your program
same thing
the infinite loop is still there
A() calls B() which calls A() which calls B()......
my code seems to work when I comment out numObj.push_back(A(b)); "test 2" is printed out
what platform are you on?
Windows
it's impossible that your program is terminating
is there an error message?
like out of memory?
idk
no nothing
no
idk how they work on windows
is there a better way to insert the constructor object into the vector then?
on linux you cant just echo $? to get the error code of the previous command
i changed everything to that and it worked
and i remove that line from B's constructor as well
yea removing that line made it work
yeah, that's the best approach
but if i wanted to push back the A object from B's constructor is there a good way
to do so?
should I just do A::A(int a):B(*this){...}?
maybe
although idk why you'd want to do this
and if B is supposed to be a super class it shouldn't be aware of A's existence
this is a general rule, ofc
The B class's vector is supposed to contain all the subclasses objects
so I call it everytime I create a new object for any class
i can't help any further for now
but i'd advice you to rethink what exactly you're trying to achieve
because this seems somewhat counterintuitive (and even dangerous)
thank you for all the help, im very thankful