Skip to content

Instantly share code, notes, and snippets.

@Infinitusvoid
Created January 15, 2023 21:11
Show Gist options
  • Save Infinitusvoid/25a2e9324bda78968fb9d4c0651d0394 to your computer and use it in GitHub Desktop.
Save Infinitusvoid/25a2e9324bda78968fb9d4c0651d0394 to your computer and use it in GitHub Desktop.
C++ : Implicit conversion example, explicit keyword
#include <iostream>
namespace Without_explicit
{
struct Entity
{
int a;
int b;
Entity(int a, int b) : a{ a }, b{ b }
{
}
Entity(int a) : a{ a }, b{ -1 }
{
}
void print()
{
std::cout << "a : " << a << " b : " << b << " \n";
}
};
void run()
{
{
Entity e = 5; //implicit conversin takes place
e.print(); //5, -1
}
{
Entity e(10, 20);
e.print(); //10, 20
}
{
Entity e = (Entity)5; //explicid conversion
e.print(); //5 - 1
}
}
}
namespace With_explicit
{
struct Entity
{
int a;
int b;
explicit Entity(int a, int b) : a{ a }, b{ b }
{
}
explicit Entity(int a) : a{ a }, b{ -1 }
{
}
void print()
{
std::cout << "a : " << a << " b : " << b << " \n";
}
};
void run()
{
//This case will not run as implicid conversion is not allowed
{
//Entity e = 5; //implicit conversin takes place
//e.print(); //5, -1
}
{
Entity e(10, 20);
e.print(); //10, 20
}
{
Entity e = (Entity)5; //explicid conversion
e.print(); //5 - 1
}
}
}
int main()
{
Without_explicit::run();
std::cout << "-----------\n";
With_explicit::run();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment