Skip to content

Instantly share code, notes, and snippets.

@Infinitusvoid
Created January 15, 2023 20:34
Show Gist options
  • Save Infinitusvoid/33532448fdd2d899e69af235d957fbc7 to your computer and use it in GitHub Desktop.
Save Infinitusvoid/33532448fdd2d899e69af235d957fbc7 to your computer and use it in GitHub Desktop.
C++ : Examples of virtual functions, without them, and with templates.
#include <iostream>
#include <string>
namespace Without_virtual_functions
{
// Without virtual functions
struct Shape
{
std::string description()
{
return "shape\n";
}
};
struct Triangle : public Shape
{
std::string description()
{
return "trinagle\n";
}
};
struct Rectangle : public Shape
{
std::string description()
{
return "rectangle\n";
}
};
void display(Shape& shape)
{
std::cout << shape.description();
}
void run()
{
Rectangle rec;
Triangle tri;
Shape shape;
display(rec); //I am shape
display(tri); //I am shape
display(shape); //I am shape
std::cout << "-------- \n";
}
}
namespace With_virtual_functions
{
// Without virtual functions
struct Shape
{
virtual std::string description()
{
return "shape\n";
}
};
struct Triangle : public Shape
{
std::string description() override
{
return "trinagle\n";
}
};
struct Rectangle : public Shape
{
std::string description() override
{
return "rectangle\n";
}
};
void display(Shape& shape)
{
std::cout << shape.description();
}
void run()
{
Rectangle rec;
Triangle tri;
Shape shape;
display(rec);
display(tri);
display(shape);
std::cout << "-------- \n";
}
}
namespace With_templates_example
{
// Without virtual functions
struct Shape
{
std::string description()
{
return "shape\n";
}
};
struct Triangle
{
std::string description()
{
return "trinagle\n";
}
};
struct Rectangle
{
std::string description()
{
return "rectangle\n";
}
};
template<typename T>
void display(T& el)
{
std::cout << el.description();
}
void run()
{
Rectangle rec;
Triangle tri;
Shape shape;
display(rec);
display(tri);
display(shape);
std::cout << "-------- \n";
}
}
int main()
{
Without_virtual_functions::run();
With_virtual_functions::run(); // virtual functions hava a peformace const as there is Vtable but't is not that much
With_templates_example::run(); // templates generate code at compile time
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment