What's the Difference?
Oct 4, 2014 at 6:14am UTC
I can not seem to grasp the difference between creating objects derived from structures/classes and creating pointers that can use the functions derived from structures/classes.
what i mean is, why do this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include <iostream>
//type players health, display players health
using namespace std;
class player{
private :
int health;
public :
void displayhealth(){
cout << health;
}
void sethealth(){
cin >> health;
}
};
int main()
{
//***************************************
player one;
player * thing; //this Section
thing = &one;
thing->sethealth();
thing->displayhealth();
//********************************
return 0;
}
when you can do this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <iostream>
//type players health, display players health
using namespace std;
class player{
private :
int health;
public :
void displayhealth(){
cout << health;
}
void sethealth(){
cin >> health;
}
};
int main()
{
//************************************
player one;
one.sethealth(); //compared to this
one.displayhealth();
//************************************
return 0;
}
Last edited on Oct 4, 2014 at 6:45am UTC
Oct 4, 2014 at 7:00am UTC
Its to do with polymorphism, where the types aren't exactly the same:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include <iostream>
struct A {
virtual void doSomething() {
std::cout << "A::doSomething\n" ;
}
};
struct B : A {
virtual void doSomething() override {
std::cout << "B::doSomething\n" ;
}
};
void func(A* a) {
a->doSomething();
}
int main() {
A a;
func(&a); // prints A::doSomething
B b;
func(&b); // prints B::doSomething
return 0;
}
Last edited on Oct 4, 2014 at 7:00am UTC
Oct 4, 2014 at 7:48am UTC
Also [smart]pointers are unavoidable (however they will probably be encapsulated inside classes) if you need to create very large objects:
1 2 3 4 5 6 7 8 9 10 11
struct big
{
char a[50 * 1024 * 1024];
};
int main()
{
// big x;
// Segmentation fault
big y = new big; // OK
}
Oct 4, 2014 at 8:34am UTC
Another reason for using a pointer would be for something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Player
{
private : int x, y;
public :
void GoNorth(int offset) { y += offset; }
/* Other functions */
int GetX() { return x; }
int GetY() { return y; }
};
class Map
{
private :
Player* MapPlayer;
public :
Map(Player& p): MapPlayer(p) {} // If Player.GoNorth() is called, player on map auto updates it's coordinates
};
Topic archived. No new replies allowed.