Thread: Confusing between Virtual and Non-virtual function

  1. #1
    Registered User
    Join Date
    May 2002
    Posts
    85

    Question Confusing between Virtual and Non-virtual function

    Code:
    class Base
    {
       public:
           Base();
           void SetData(int data) { m_data = data; }
           int    GetData() { return m_data; }
           virtual void PrintData() { cout << "Data value: " << m_data; }
      private:
          int m_data;
    }
    
    class Derive : public Base
    {
       public:
          Derive()
          void SetX( float x)  { m_Value = x; }
          void void PrintData() { cout << " Value: " << m_Value; }
       private:
          float m_Value;
    }
    
    int main()
    {
        Derive D;
        D.SetData(4);   // it works even not defined in Derive class? 
        int data1 = D.GetData();  // Also work
        return 0;
    }
    Hm... even SetData() and GetData() methods are not defined in Drive class, but there is no syntax error when these methods are called with Derive class .
    Anyone knows why?
    Last edited by dv007; 01-11-2006 at 12:46 PM.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    847
    A derived class contains the functions of the base class. Virtual functions allow your derived classes to have different function with the same name.

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Hm... even SetData() and GetData() methods are not defined in Drive class...

    D.SetData(4); // it works even not defined in Derive class?
    It's because of something called inheritance. That's what this does:
    Code:
    : public Base

  4. #4
    Registered User
    Join Date
    Nov 2005
    Posts
    85
    You are saying that each class has its own print function, you could call the superclass print function by saying Base::PrintData();

Popular pages Recent additions subscribe to a feed