pointers to objects

why do we need them?

and what does this mean:

 
Monster* checkRandomEncounter();


its located inside the other class, and Monster is another class...

ty in advance!
Monster* checkRandomEncounter(); means that the function checkRandomEncounter returns a pointer to Monster


Pointers are used for many reasons, see these:
http://www.cplusplus.com/doc/tutorial/pointers/
http://www.cplusplus.com/doc/tutorial/dynamic/
http://en.wikipedia.org/wiki/Pointer
In C/C++, you are allowed to address memory directly. C uses pointers to reference a piece of memory. C++ can use pointers and references.

For example, if you were given an address of an integer 0x14380, you could declare a variable that pointed to that address as: int* number = 0x14380;

You could assign it a value *number = 7;

An you could print it: std::cout << *number << std::endl;

C/C++ has named variables and unnamed variables. Named variables are variables that you declare as global, local or function parameters. Unnamed variables can be obtained from the heap or reference named variables and must be handled using pointers (or references).

Monster* checkRandomEncounter(); declares a function that returns a pointer to type called Monster.

the problem was i didnt knew that you can use pointers as a return value of functions, but ty anyway

but the question is very specific: why do we need pointers to OBJECTS? i know you can use them, if u what nothing to happen, but for what else?
Yes you need pointers to objects. Polymorphism works thru pointers to a base class.

You can return an object allocated from the heap.
1
2
3
4
5
6
7
8
9
10
11
12
Shape* CreateRandomShape()
{
    switch (rand() % 3)
    {
    case 0:
        return new Circle();
    case 1:
        return new Square();
    case 2:
        return new Triangle();
    }
}


You should never return an object allocated on the stack.
1
2
3
4
5
Shape* BadCreate()
{
    Triangle localShape;
    return &localShape;  // never do this
}
Last edited on
Topic archived. No new replies allowed.