Thread: Virtual functions in subclass

  1. #1
    Registered User
    Join Date
    Dec 2009
    Posts
    41

    Virtual functions in subclass

    So I was looking through some code for a project trying to debug it, and I ran into a gap in my understanding. The basic question is, what is the purpose of the "virtual" keyword before overridden functions in the sub class.

    For example(stolen from Microsoft's website:

    Code:
    #include <iostream> 
    #include <string> 
    using namespace std;
     
    class BasePoint { 
    public:
    	BasePoint(int px, int py):x(px),y(py) {} 
    	int x, y; //position 
    	virtual string type() = 0;
    	virtual void info() { 
    		cout << endl << "figure: " << type() << endl;
    		cout << "position: x=" << x << ", y=" << y << endl;
    	} 
    };
     
    class Figure1P : public BasePoint { 
    public:
    	Figure1P(int px, int py, int r):p1(r),BasePoint(px, py) {} 
    	int p1;
    	virtual void info() { 
    		BasePoint::info();
    		cout << "property 1: p=" << p1 << endl;
    	} 
    };
     
    class Square : public Figure1P { 
    public:
    	Square(int px, int py, int r):Figure1P(px, py, r) {};
    	virtual string type() { 
    		return "square";
    	} 
    };
     
    class Circle : public Figure1P { 
    public:
    	Circle(int px, int py, int r):Figure1P(px, py, r) {} 
    	virtual string type() { 
    		return "circle";
    	} 
    };
     
    class Figure2P : public Figure1P { 
    public:
    	Figure2P(int px, int py, int w, int h):p2(h),Figure1P(px, py, w) {} 
    	int p2;
    	virtual void info() { 
    		Figure1P::info();
    		cout << "property 2: p=" << p2 << endl;
    	} 
    };
     
    class Rectangle : public Figure2P { 
    public:
    	Rectangle(int px, int py, int w, int h):Figure2P(px, py, w, h) {} 
    	virtual string type() { 
    		return "rectangle";
    	} 
    };
     
    class Oval : public Figure2P { 
    public:
    	Oval(int px, int py, int w, int h):Figure2P(px, py, w, h) {};
    	virtual string type() { 
    		return "oval";
    	} 
    };
     
    int main(void) { 
    	BasePoint **objs = new BasePoint*[5]; 
    	// allocate space for 10 BasePoint pointers,  
    	// they may be used to store derived classes 
     
    	// creating objects 
    	objs[0] = new Circle(7, 6, 55);
    	objs[1] = new Rectangle(12, 54, 21, 14);
    	objs[2] = new Square(19, 32, 10);
    	objs[3] = new Oval(43, 10, 4, 3);
    	objs[4] = new Square(3, 41, 3);
     
    	bool flag=false; 
    	do { 
    		cout << endl << "We have 5 objects with numbers 0..4" << endl;
    		cout << "Enter object number to view information about it " << endl;
    		cout << "Enter any other number to quit " << endl;
    		char onum; // in fact, this is a character, not a number 
    		// this allows user to enter letter and quit... 
    		cin >> onum;
     
    		// flag -- user have entered number 0..4 
    		flag = ((onum >= '0')&&(onum <= '4'));
     
    		if (flag) 
    			objs[onum-'0']->info();
     
    	} while(flag);
     
    	// freeing memory 
    	for(int i=0;i<5;i++) 
    		delete objs[i];
     
    	delete [] objs;
    }
    In all the base classes, such as circle, the type() function is overridden. why is the virtual keyword used?

    Code:
    	Circle(int px, int py, int r):Figure1P(px, py, r) {} 
    	virtual string type() { 
    		return "circle";
    	}
    I removed the virtual keywords and it compiled and ran fine.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by somekid413
    In all the base classes, such as circle, the type() function is overridden. why is the virtual keyword used?
    To document the fact that the member function is virtual.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Dec 2009
    Posts
    41
    So it doesn't add or change functionality? Kind of just a prettier way to make a comment saying its virtual?

    also, holy crap you're a fast responder

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Yes.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    Virtual does mean something very important.
    By placing the keyword virtual before a method declaration it says that when referring to an instance of a superclass by a pointer or reference to a base class that the correct implementation should be resolved at run time and that the "highest level" implementation should be used.
    As well you must use virtual when declaring pure virtual methods. However note that many compilers adhering to the previous standard will not require virtual in the implementations in the derived classes. This, IMO, is bad mojo. I believe the new standard requires the virtual keyword in the declaration in the derived classes as well. If the method is declared as virtual I would also denote this in the derived class method to make the code simpler to read. Otherwise you force the dev to navigate all the way back to the base class to determine which methods are virtual and/or pure virtual.
    Last edited by VirtualAce; 04-01-2012 at 10:29 AM.

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by VirtualAce
    As of the new standard I believe the compiler forces the virtual to be there in the derived classes
    The final draft of C++11 does not have such a requirement.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    Nice. Perhaps it is Microsoft that is going to enforce this in their compiler. I thought I read that this was going to be enforced in the new standard....as it should be.

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    A warning would be more appropriate since this is not a new feature. If it is an error, then it means that existing valid code could break.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    Yes a warning would be the ideal approach and the only one I would think a compiler dev team would take since an error, like you said, would break existing code. But I have never been able to simply migrate code from built with one compiler version to another version without some massaging. As long as existing code is not recompiled on the new version it won't break. I remember migrating from 2003 to 2008 and oh what a pain it was given all the 3rd party libraries that were involved that I did not have access to and could not recompile on the new version. Fun times.
    Last edited by VirtualAce; 04-01-2012 at 10:53 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Virtual functions
    By SterlingM in forum C++ Programming
    Replies: 12
    Last Post: 11-03-2009, 11:51 AM
  2. Virtual Functions
    By warfang in forum C++ Programming
    Replies: 2
    Last Post: 05-07-2007, 11:14 PM
  3. Virtual functions but non-virtual destructor
    By cunnus88 in forum C++ Programming
    Replies: 4
    Last Post: 03-31-2007, 11:08 AM
  4. Virtual Functions
    By guda in forum C++ Programming
    Replies: 3
    Last Post: 11-16-2004, 04:13 PM
  5. virtual functions?
    By kohatian3279 in forum C++ Programming
    Replies: 1
    Last Post: 01-10-2003, 09:34 AM