how get instanace-class-name of a variable

U

unknown;

hi,

i've got the following classes:

class CImage {}
class CImageBlackWhite : public CImage {}
class CImageColor : public CImage {}

and i've got a global function


void function_name (CImage * image) {

if image is instace of CImageBlackWhite {
do something
}

else if image is instance of CImageColor {
do something else
}

return;
}



my question/problem:

i don't know how to get the name of the class from the variable image.


thanks!!
 
N

Noah Roberts

unknown; said:
hi,

i've got the following classes:

class CImage {}
class CImageBlackWhite : public CImage {}
class CImageColor : public CImage {}

and i've got a global function


void function_name (CImage * image) {

if image is instace of CImageBlackWhite {
do something
}

else if image is instance of CImageColor {
do something else
}

return;
}



my question/problem:

i don't know how to get the name of the class from the variable image.

Look up Liskov Substitution Principle (spelling probably not correct)
to find out why this is bad design. Look up dynamic_cast and the
typeof operator to learn how to do it.
 
E

Evan

unknown; said:
hi,

i've got the following classes:

class CImage {}
class CImageBlackWhite : public CImage {}
class CImageColor : public CImage {}

and i've got a global function


void function_name (CImage * image) {

if image is instace of CImageBlackWhite {
do something
}

CImageBlackWhite * cibw = dynamic_cast<CImageBlackWhite*>(image);
if(cibw) {
do something
}
else if image is instance of CImageColor {
do something else
}

CImageColor* cic = dynamic_cast<CImageColor*>(image);
if(cic) {

return;
}

However, Noah is right in his other post; this is a bad code smell.
There is often a better approach. The typical method is to add a
virtual method to CImage. CImageBlackWhite::foo (where foo is the new
virtual method) would then "do something" and CImageColor::foo would
"do something else". Then function_name would just call image->foo().

But unfortunately, this is not always possible to do. In particular, if
the CImage heirarchy is not under your control, you can't change it.

Evan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,792
Messages
2,569,639
Members
45,352
Latest member
SherriePet

Latest Threads

Top