Reduce Repetition: How to Use the using Keyword for OOP in C++
C++ "using" keyword

Reduce Repetition: How to Use the using Keyword for OOP in C++

C++ is a versatile and powerful programming language known for its flexibility and robust feature set. The "using" keyword stands as a valuable tool for simplifying code, managing namespaces, and enhancing readability. In this article, we will explore the multifaceted applications of the "using" keyword in C++.

To create an alias for a namespace

using namespace std;        

This allows you to use things from the std namespace without prefixing them, like cout instead of std::cout.

To create an alias for a type

using int64 = long long;        

This creates int64 as an alias for long long type.

To import specific items into the current namespace

using std::string;
using std::cout;        

This imports only string and cout from std namespace

To declare a base class function is overridden in the derived class

using namespace std;

class Base
{
public:
  void function()
  {
    std::cout << "function()" << std::endl;
  }
};

class Derived : public Base
{
public:
  using Base::function; // you can use base class func
};

int main()
{
  Base b;
  b.function();
}        
function()        

This helps to use base class functions in a derived class object.

We can define any overloaded function in the base class as the following example code.

#include <iostream>

class Base 
{
public:
  void func(int x) 
  {
    std::cout << "Base func(int) " << x << std::endl;
  }
  
  void func(double x) 
  {
    std::cout << "Base func(double) " << x << std::endl; 
  }
};

class Derived : public Base 
{
public:
  using Base::func;

  void func(char x) 
  {
    std::cout << "Derived func(char) " << x << std::endl;  
  }

  void func(int a, int b) 
  {
    std::cout << "Derived func(int, int) " << a << " " << b << std::endl;
  }
};

int main() 
{
  Derived d;
  d.func(5); // Calls Base func(int)
  d.func(3.14); // Calls Base func(double) 
  d.func('A'); // Calls Derived func(char)
  d.func(1, 2); // Calls Derived func(int, int)

  return 0;
}        
Base func(int) 5
Base func(double) 3.14
Derived func(char) A
Derived func(int, int) 1 2        

To import constructors from the base class to the derived class

class Base 
{
  Base(int);
}

class Derived : Base {
  using Base::Base; // imports constructors
}        

This is the same as the previous point.

Bonus point

You can access protected variables in the base class from the derived class.

#include <iostream>

class Base {
protected:
  int a = 10;
};

class Derived : public Base {
public:
  using Base::a;
};

int main() {
  Derived d;
  std::cout << "Base value : " << d.a << std::endl;
  return 0;
}        
Base value : 10        



要查看或添加评论,请登录

Lahiru Dilshan的更多文章

社区洞察

其他会员也浏览了