Skip to content

Instantly share code, notes, and snippets.

@sebastiangeiger
Created October 26, 2011 11:14
Show Gist options
  • Save sebastiangeiger/1316063 to your computer and use it in GitHub Desktop.
Save sebastiangeiger/1316063 to your computer and use it in GitHub Desktop.
Polymorphism in C++
#include <iostream>
#include <string.h>
#include <boost/tr1/memory.hpp>
class Image {
public:
Image(std::string className = "Image")
: className_(className)
{}
virtual ~Image() {}
virtual std::string className() {
return className_;
}
private:
std::string className_;
void operator=(const Image&);
};
class RightImage : public Image {
public:
RightImage()
: Image("RightImage")
{}
};
class Processor{
public:
void highLevelProcessing(Image& image){
process(image);
}
void highLevelProcessing(Image* image){
process(image);
}
private:
void process(Image& image){
std::cout << "Invoking process(Image& image) with image of type \"" << image.className() << "\"" << std::endl;
}
void process(RightImage& rightImage){
std::cout << "Invoking process(RightImage& rightImage) with rightImage of type \"" << rightImage.className() << "\"" << std::endl;
}
void process(Image* image){
std::cout << "Invoking process(Image* image) with image of type \"" << image->className() << "\"" << std::endl;
}
void process(RightImage* rightImage){
std::cout << "Invoking process(RightImage* rightImage) with rightImage of type \"" << rightImage->className() << "\"" << std::endl;
}
};
int main(int argc, char **argv) {
std::tr1::shared_ptr<Image> rightImageSharedPtr(new RightImage());
Image* rightImagePointer = new RightImage();
RightImage rightImage;
Processor processor;
std::cout << "value: ";
processor.highLevelProcessing(rightImage);
std::cout << "shared_ptr: ";
processor.highLevelProcessing(*rightImageSharedPtr);
std::cout << "old fashioned pointer 1: ";
processor.highLevelProcessing(*rightImagePointer);
std::cout << "old fashioned pointer 2: ";
processor.highLevelProcessing(rightImagePointer);
}
@sebastiangeiger
Copy link
Author

value: Invoking process(Image& image) with image of type "RightImage"
shared_ptr: Invoking process(Image& image) with image of type "RightImage"
old fashioned pointer 1: Invoking process(Image& image) with image of type "RightImage"
old fashioned pointer 2: Invoking process(Image* image) with image of type "RightImage"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment