+ Reply to Thread
Results 1 to 3 of 3

Thread: What is inheritance in C++?

  1. #1

    What is inheritance in C++?

    Hi All,

    I am newbie to C++ world.

    What is inheritance in C++?

    Can anyone give me some example?

    How to use it in real-time application?

    Thanks.

  2. #2
    Inheritance can be used to reuse code.

    It allows classes to be inherited by another classes.

    A class being inherited is called base class.

    A class who inherits a base class is called derived class.

    Example:

    Code:
    class CEmployee
    {
    	int			m_nEmployeeCode ;
    	std::string	        m_strName ;
    	int			m_nSalary ;
    public:
    
    	CEmployee(int nEmployeeCode, const std::string strName, int nSalary)
    	{
    		m_nEmployeeCode = nEmployeeCode ;
    		m_strName		= strName ;
    		m_nSalary		= nSalary ;
    	}
    
    	int GetEmployeeCode()
    	{
    		return m_nEmployeeCode ;
    	}
    
    	std::string GetName()
    	{
    		return m_strName ;
    	}
    
    	int GetSalary()
    	{
    		return m_nSalary ;
    	}
    
    	virtual void DoTask() {} ;
    } ;
    
    class CManager : public CEmployee
    {
    public:
    	CManager(int nEmployeeCode, const std::string strName, int nSalary)
    		: CEmployee(nEmployeeCode, strName, nSalary)
    	{
    	}
    
    	virtual void DoTask()
    	{
    		char szMessage[256] ;
    		sprintf(szMessage, "I am doing Manager's task\n") ;
    		OutputDebugString(szMessage) ;
    	} ;
    } ;
    
    class CClerk : public CEmployee
    {
    public:
    	CClerk(int nEmployeeCode, const std::string strName, int nSalary)
    		: CEmployee(nEmployeeCode, strName, nSalary)
    	{
    	}
    
    	virtual void DoTask()
    	{
    		char szMessage[256] ;
    		sprintf(szMessage, "I am doing Clerk's task\n") ;
    		OutputDebugString(szMessage) ;
    	} ;
    } ;
    
    void PrintEmployeeData(CEmployee *pEmployee)
    {
    	int nEmployeeCode	= pEmployee->GetEmployeeCode() ;
    	std::string strName = pEmployee->GetName() ;
    	int nSalary			= pEmployee->GetSalary() ;
    	pEmployee->DoTask() ;
    }
    
    void UseInheritance()
    {
    	CEmployee *pManager = new CManager(1, "Roger", 10000) ;
    	PrintEmployeeData(pManager) ;
    
    	CEmployee *pClerk = new CClerk(10, "Craig", 7000) ;
    	PrintEmployeeData(pClerk) ;
    }

  3. #3
    Thank you for your response and example.

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts