tags:

views:

30

answers:

1

I a new at OO programming and trying to clear up a few things.

When you instatiate a class and create an object, Ive seen the following:

 class Program
    {
        static void Main(string[] args)
        {
            MyClassA a = new MyClassA();

            MyClassA b = a;

            MyClassA c = b;

            c.DoSomething();
            Console.ReadLine();

        }
    }
    public class MyClassA
    {
        public void DoSomething()
        {
            Console.WriteLine("I am from Class A");
        }
    }

This may be a bad example, but the question I am trying to get answered is: Why is pointing one object reference to another important or why\where is it used? Why not use the object you created in the first place?

A: 

This is more Java than generically "object-oriented" -- C++ would be completely different (if you need to "refer" to objects, and change to what object a certain variable "refers" to, you need to use explicit pointers -- references in C++ cannot be "reseated").

Anyway, unconditionally creating synonyms like in your example has no point nor purpose. Much more typical uses would be, for example,

MyClass a = ...whatever...;
MyClass b = ...whatever else...;
MyClass c;
if(something()) {
    c = a;
} else {
    c = b;
}
c.dosomething();
c.blahblah();
c.andmore();

i.e., having a "synonym" that can refer to one object, or to another one, depending on circumstances, so that following operations can always be coded as being "on the synonym" and they'll be on the "right" object either way (alternatives such as duplicating the whole blocks of "following operations" are, at the very least, very bad and repetitious style, and, e.g. when some of the "following operations" are in other methods and the "synonym" is an instance variable rather than a local variable, can be extremely hard to code, too).

This is just the simplest example, of course. But, do you really need other, more complicated ones?-)

Alex Martelli