I have a such syntax in program
/* The Object1 is allowed to be changed */
class Object1 : BaseClass {
BaseClass *link;
int i;
public:
Object1(int a){i=a;}
Object1(int a, Object1 /*place1*/ o) {i=a; link= &o;}
};
int main(){
/* The initialization syntax must be preserved. No any new(), no other local objects b,c */
Object1 a(1, /*place2*/ Object1(2));
...
}
What do I need in place1? I want to save a link (pointer) to the second object in the first object. Should I use in place1 reference “&”?
What type will have “Object1(2)” in place2? Is it a constructor of the anonymous object? Will it have a “auto” storage type?
Thanks
UPDATE:
In the place2, the syntax is fixed and I really must support creating of “chain”, like
Object1 a(1, Object1(2, Object1(6, Object1(999753))));
I can’t add any symbol in the definiton of a.
UPDATE2:
for place1: Object1(int a, Object1 &o) {i=a; link= &o;} and Object1 a(1, Object1(2)); in place2 I have a compile error (g++):
main.cpp||In function `int main()':|
main.cpp|19|error: no matching function for call to `Object1::Object1(int, Object1)'|
main.cpp|9|note: candidates are: Object1::Object1(const Object1&)|
main.cpp|14|note: Object1::Object1(int, Object1&)|
main.cpp|13|note: Object1::Object1(int)|
In “place1”, you need a reference.
Object1isn’t fully defined, so you can’t take it by value. That said, you wouldn’t want to pass by value; when you take the address of it, you’d be getting the address of the copy, not the actual object.Since you only want a pointer to a
BaseClass, it might make more sense to only place that restriction on the parameter. (Of course, if you really need anObject1, reflect that in the type oflink:Object1* link;).Also consider using an initialization list:
Always use an initialize list.
“place2” creates an unnamed instance of
Object1using a constructor. It hasno storage(?)autostorage, and dies at the end of the expression.That is, once you’ve hit the semicolon in
Object1 a(1, /*place2*/ Object1(2));, it ceases to exist and you have a pointer to an non-existent object! This results in undefined behavior.Give it a lifetime beyond the expression:
Always make sure that when you refer an object, it will live the entire time you refer to it.
Your new compile error is because you can’t have a reference to a temporary variable. You can have one with a const-reference, though. The thing is, your pointer needs to point to a
const BaseClassnow, which may dampen what you want.Again, your design needs reworking, unfortunately.