|
-
Jul 20th, 2007, 04:13 AM
#1
Thread Starter
Addicted Member
[RESOLVED] What is the purpose of ...base *bptr; bptr=new derive();
Hi All!
i have a doubt in c++,
Asume there are two classes, "Base" is a base class, "derive" is a derived class that derived from "Base".
egg:
class Base
{.....
....
};
class Derive public:Base
{
........
........
};
int main()
{
Base *bptr;
bptr=new Derive();//**** What is this meaning, and purpose?
.........
}
(a): why the object of derived class is to be assigned to base class pointer?(eventhough the derived class's object cotains both base class, and derived class's data)
(b): what the object pointer(bptr), holds?(whether it is pointing to base class or derived class)?
pls let me know the differnces between derived class object and the above mentioned bptr's content
Thanks in advance:
regards:
raghunadhs.
-
Jul 20th, 2007, 04:31 AM
#2
Re: What is the purpose of ...base *bptr; bptr=new derive();
Ah, polymorphism.
Basically, the purpose of something like that is to allow you to edit higher classes, through the more abstract class. For example, pretend we have a base class called Entity. The following classes inherit from Entity:
Soldier
SoldierWithHorse
Wizard
Orc
If you want to edit values common to all of them (those inherited from the base class), then you can do something like this (using Health as an example):
Code:
class Entity
{
public:
int Health;
};
class Soldier : public Entity {};
class SoldierWithHorse : public Entity {};
void AddToHealth(Entity *ent)
{
ent->Health += 5;
}
int main()
{
Soldier *soldier = new Soldier();
SoldierWithHorse *soldier2 = new SoldierWithHorse();
AddToHealth(soldier);
AddToHealth(soldier2);
std::cout << soldier->Health;
delete soldier;
delete soldier2;
}
The above, would output "5", for both the soldier, and the soldier with a horse.
Without knowing the internals, I would assume that bptr is a type of "private pointer", that can only access the Base classes attributes.
chem
Visual Studio 6, Visual Studio.NET 2005, MASM
-
Aug 15th, 2007, 01:13 PM
#3
Thread Starter
Addicted Member
Re: What is the purpose of ...base *bptr; bptr=new derive();
Hi chemicalnova,
Sorry for the long delay... Explenation is too good. thank u very much
regards:
raghunadhs
[QUOTE=chemicalNova]Ah, polymorphism.
Basically, the purpose of something like that is to allow you to edit higher classes, through the more abstract class. For example, pretend we have a base class called Entity. The following classes inherit from Entity:
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|