English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Inheritance Explanation and Example Code

 C++inheritance can be single inheritance or multiple inheritance, and each inheritance connection can be public, protected, private, or virtual or non-virtual. Then, the options for each member function can be virtual or non-virtual or pure virtual. This article only verifies some key points.

  public inheritance, for example:

1 class base
2 {...}
3 class derived:public base
4 {...}

  If written this way, the compiler will understand that an object of type derived is also an object of type base, but an object of type base is not an object of type derived. This is very important. Then, a function parameter of type base is applicable to derived, but a function parameter of type derived is not applicable to base. The following is the verification code, a function with a parameter of type base, passing derived should succeed, on the contrary, a function with a parameter of type derived

#include <iostream>
#include <stdio.h>
class base
{
  public:
  base()
  :baseName(""),baseData(0)
  {}
  base(std::string bn,int bd)
  :baseName(bn),baseData(bd)
  {}
  std::string getBaseName() const
  {
    return baseName;
  }
  int getBaseData()const
  {
    return baseData;
  }
  private:
    std::string baseName;
    int baseData;
};
class derived:public base
{
  public:
    derived():base(),derivedName("")
    {}
    derived(std::string bn,int bd,std::string dn)
    :base(bn,bd),derivedName(dn)
    {}
    std::string getDerivedName() const
    {
      return derivedName;
    }
  private:
    std::string derivedName;
};
void show(std::string& info,const base& b)
{
  info.append("Name is ");
  info.append(b.getBaseName());
  info.append(", baseData is ");
  char buffer[10];
  sprintf(buffer,"%d",b.getBaseData());
    info.append(buffer);
}
int main(int argc, char* argv[])
{
  base b("test",10);
  std::string s;
  show(s,b);
  std::cout<<s<<std::endl;
  derived d("btest",5,"dtest");
  std::string ss;
  show(ss,d);
  std::cout<<ss<<std::endl;
  return 0;
}

The running result is:

base:baseName is test, baseData is 10
base:baseName is btest, baseData is 5

Modify the code below to change the function parameter to derived

void show2(std::string& info, const derived& d)
{
  info.append("Name is ");
  info.append(d.getBaseName());
  info.append(", baseData is ");
  char buffer[10];
  sprintf(buffer,"%d",d.getBaseData());
  info.append(buffer);
}

The compiler reports an error when calling show(ss,d);

1 derived_class.cpp: In function `int main(int, char**)':
2 derived_class.cpp:84: error: invalid initialization of reference of type 'const derived&' from expression of type 'base'
3 derived_class.cpp:70: error: in passing argument 2 of `void show2(std::string&, const derived&)

The second point verifies various forms of inheritance, first giving a table

Inheritance method \ member type public protected private
public public protected Cannot inherit
protected protected protected Cannot inherit
private private private Cannot inherit

Here is an explanation, it simply expresses the members of the base class, which are inherited by public, protected, and private, and the types of the members in the original base class are public, protected, and private in the inherited class, as shown in the table

class base
{
  public:
    std::string testPublic()
    {
      return std::string("this is public base");
    }
  protected:
    std::string testProtected()
    {
      return std::string("this is protected base");
    }
  private:
    std::string testPrivate()
    {
      return std::string("this is private base");
    }
};
class derivedPublic:public base
{
  public:
    std::string testPubPublic()
    {
      return testPublic()+= "in derived";
    }
    std::string testProPublic()
    {  
      return testProtected()+= "in derived";
    }
    std::string testPriPublic()          
    {  
      return testPrivate()+= "in derived";
    }
};
int main(int argc, char* argv[])
{
  derivedPublic dpub;
  std::cout << dpub.testPublic() << std::endl; 
}

Report the following error, indicating that testPrivate() is not a derived private function but a base private function

derived11.cpp:16: error: `std::string base::testPrivate()' is private
derived11.cpp:36: error: within this context

This verifies that private type members cannot be inherited (public, private, protected). Note: private and protected are omitted from the proof.

We only need to verify that testProtected can be inherited by the third-level derived class but cannot be directly called by the third-level class, which indicates that it is inherited as a protected type after public inheritance, and if the base class has public type members, they can be inherited and directly called.

#include <iostream>
#include <string>
class base
{
  public:
    std::string testPublic()
    {
      return std::string("this is public base");
    }
  protected:
    std::string testProtected()
    {
      return std::string("this is protected base");
    }
  private:
    std::string testPrivate()
    {
      return std::string("this is private base");
    }
};
class derivedPublic:public base
{
  public:
    std::string testPubPublic()
    {
      return testPublic()+= "in derived";
    }
    std::string testProPublic()
    {  
      return testProtected()+= "in derived";
    }
//    std::string testPriPublic()          
//    {  
//      return testPrivate()+= "in derived";
//    }
};
class deepDerived:public derivedPublic
{
  public:
    std::string deepProtected()
    {
      return testProtected() +="in deep";
    }
    std::string deepPublic()
    {
      return testPublic() +="indeep";
    }
};
int main(int argc, char* argv[])
{
  derivedPublic dpub;
  std::cout << dpub.testProtected() << std::endl; 
  deepDerived deepdpub;
  std::cout << deepdpub.testPublic() << std::endl;
  std::cout << deepdpub.testProtected() << std::endl;
  std::cout << deepdpub.deepProtected() << std::endl;
  std::cout << deepdpub.deepPublic() << std::endl;
}

Here the server reports an error

derived12.cpp:13: error: `std::string base::testProtected()' is protected
derived12.cpp:62: error: within this context

This verifies that one is public and the other is protected. Protected cannot be directly called, but it can be called by public members after inheritance.
The detailed steps are omitted here for brevity. If you are interested in the verification of this part, you can check the code below.

#include <iostream>
#include <string>
class base
{
  public:
    std::string testPublic()
    {
      return std::string("this is public base");
    }
  protected:
    std::string testProtected()
    {
      return std::string("this is protected base");
    }
  private:
    std::string testPrivate()
    {
      return std::string("this is private base");
    }
};
class derivedPublic:public base
{
  public:
    std::string testPubPublic()
    {
      return testPublic()+= "in derived";
    }
    std::string testProPublic()
    {  
      return testProtected()+= "in derived";
    }
//    std::string testPriPublic()          //Private members are not inherited
//    {  
//      return testPrivate()+= "in derived";
//    }
};
class deepDerived:public derivedPublic
{
  public:
    std::string test()
    {
      return testPublic() +="in 3";
    }
};
class derivedProtected:protected base
{
  public:
    std::string testPubProtected()
    {
      return testPublic()+= "in derived";
    }
    std::string testProProtected()
    {  
      return testProtected()+= "in derived";
    }
};
class deepDerived2:public derivedProtected
{
  public:
    std::string test()
    {
      return testPublic() +="in 3";
    }
};
class derivedPrivate:private base
{
  public:
    std::string testPubPirvate()
    {
      return testPublic()+= "in derived";
    }
    std::string testProPrivate()
    {  
      return testProtected()+= "in derived";
    }
};
//class deepDerived3:public derivedPrivate
//{
//  public:
//    std::string test()
//    {
//      return testPublic() +="in 3";
//    }
//};
int main(int argc, char* argv[])
{
  derivedPublic dpub;
  //derivedProtected dpro;
  //derivedPrivate dpri;
  std::cout << dpub.testPublic() << std::endl;    //
  //std::cout << dpub.testProtected() << std::endl;  //Users inherited cannot be used either
  //cout << dpub.testPrivate() << std::endl;     //All base classes are private functions
  std::cout << dpub.testPubPublic() << std::endl;
  std::cout << dpub.testProPublic() << std::endl;
  //std::cout << dpub.testPriPrivate() << std::endl; //Not inherited
  deepDerived dd;
  std::cout << dd.test() << std::endl;
  derivedProtected dpro;
  //std::cout << dpro.testPublic() << std::endl;    //Changed to protected type
  std::cout << dpro.testPubProtected() << std::endl;
  std::cout << dpro.testProProtected() << std::endl;
  deepDerived2 dd2;
  std::cout << dd2.test() << std::endl;
  derivedPrivate dpri;
  std::cout << dpri.testPubPirvate() << std::endl;
  std::cout << dpri.testProPrivate() << std::endl;
//  deepDerived3 dd3;
//  std::cout << dd3.test() << std::endl;
}

The above is the C++ The materials compiled by j, and will continue to supplement relevant materials, thank you all for your support to this site!

Statement: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please send an email to codebox.com (replace # with @ when sending an email) to report any violations, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.