How to"link" an object to another one

Jun 27, 2013 at 1:30am
Hello.
I have the following problem, I have an object of a class Subject, and I want that this object points to another object of class Classes, creating a kind of link.

How can I do that?

Thanks
Jun 27, 2013 at 3:42am
Well, I don't think that can work.

If I'm understanding you correctly, then are you trying to do something like this?
1
2
Class1 *inst1=new Class1;
Class2 *inst2=inst1;


For one, that won't work. Remember, an object of a class is an instance of a class. So the instance can't "point" to another instance, that doesn't make sense. What you can do is have the variable that holds the instance point to another instance of the same class. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Fooey
{
public:
    int member;
};

int main() {
Fooey *var1=new Fooey;     //Both var1 & var2 have separate instances of class "Fooey"
Fooey *var2=new Fooey;

Fooey *var3=var1;          //var 3 now points to var1's instance of "Fooey"

var3=var2;                 //var3 now points to var2's instance of "Fooey"
       }


But notice that when I changed what var3 points to, it had to be a var that pointed to the same class. You can't declare a variable pointing to one type of class, and then try to point that variable to a different class. After all, they're completely different types. It's the same thing if you tried doing this:
1
2
3
bool derp=true;
char merp='Z';
derp=merp;      //Doesn't work because `derp' can't hold a char, it's a bool! 


edit: example fail.
Last edited on Jun 29, 2013 at 1:23am
Jun 27, 2013 at 4:10am
1
2
3
4
5
6
7
8
9
10
class Subject{
public:
   Classes *link;
};

int main(){
   Classes foo;
   Subject bar;
   bar.link = &foo;
}



> Doesn't work because `derp' can't hold a char, it's an int!
try it.
Last edited on Jun 27, 2013 at 4:11am
Jun 29, 2013 at 1:24am
ne555 said:
> Doesn't work because `derp' can't hold a char, it's an int!
try it.


Whoops, your right. Now time for a better example.....lol
Jul 1, 2013 at 3:20am
thank you people, lol for the derp example.
I solved here :)
Topic archived. No new replies allowed.