ambuli
asked on
Basic Polimorphism question
Hi Experts,
I have the following
class A
{
};
class B : public A
{
};
class C: public B
{
}
class D
{
public:
void someFunction(A *a);
};
Can I do the following??
A *aa = new A( );
B *bb = new B( );
C *cc = new C( )
someFunction(aa);
someFunction(bb);
someFunction(cc);
I have the following
class A
{
};
class B : public A
{
};
class C: public B
{
}
class D
{
public:
void someFunction(A *a);
};
Can I do the following??
A *aa = new A( );
B *bb = new B( );
C *cc = new C( )
someFunction(aa);
someFunction(bb);
someFunction(cc);
Yes, of course you can:
class A
{
};
class B : public A
{
};
class C: public B
{
};
class D
{
public:
void someFunction(A *a);
};
void D::someFunction(A* a)
{
}
int main ()
{
A *aa = new A( );
B *bb = new B( );
C *cc = new C( );
D d;
d.someFunction(aa);
d.someFunction(bb);
d.someFunction(cc);
return 0;
}
C:\tmp\cc>cl baspoly.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8804 for 80x86
Copyright (C) Microsoft Corp 1984-1998. All rights reserved.
baspoly.cpp
Microsoft (R) Incremental Linker Version 6.00.8447
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.
/out:baspoly.exe
baspoly.obj
But, keep in mind that you only will be able to access the 'A' aspect of teh object passed in, everything else would require a typecast.
class A
{
};
class B : public A
{
};
class C: public B
{
};
class D
{
public:
void someFunction(A *a);
};
void D::someFunction(A* a)
{
}
int main ()
{
A *aa = new A( );
B *bb = new B( );
C *cc = new C( );
D d;
d.someFunction(aa);
d.someFunction(bb);
d.someFunction(cc);
return 0;
}
C:\tmp\cc>cl baspoly.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8804 for 80x86
Copyright (C) Microsoft Corp 1984-1998. All rights reserved.
baspoly.cpp
Microsoft (R) Incremental Linker Version 6.00.8447
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.
/out:baspoly.exe
baspoly.obj
But, keep in mind that you only will be able to access the 'A' aspect of teh object passed in, everything else would require a typecast.
ASKER
Again, the same problem. If one of the object is multiple inherited... Sorry, I was thinking the multiple inheritiance shouldn't matter and simpilified the problem. So, I guess, I cannot do this with multiple inheritance...
class A{};
class B: public A{};
class X:public A{};
class C: public B, public X{};
class A{};
class B: public A{};
class X:public A{};
class C: public B, public X{};
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
aa "is a" A.
bb "is a" A, since a B "is a" A.
Anything that' s a subclass of A can be used where an A is expected.
Incidentally, that's not even polymorphism, that's just straight inheritance.