Introduction to Programming and C++

Contents Previous Topic Next Topic

It is possible to call a member function on a zero pointer, as is demonstrated in Program 1, however, in many cases, this would suggest a flaw in the design.

Program 1. Checking for this == 0.

class Complex {
	private:
		double re, im;

	public:
		Complex( double r = 0.0, double i = 0.0 ):re( r ), im( i ) {
			// empty constructor
		}

		double real() const {
			if ( this == 0 ) {
				// accessing 're' or 'im' will cause a crash
				return 0.0;
			} else {
				return re;
			}
		}
};

A member function which checks if this == 0 cannot access any of the class members. Doing so will cause a segmentation fault, that is, your program is attempting to access an invalid memory location.


Questions

1. Download example.cpp and try it out.

2. Is the design of the code in Question 1 advisable?


Contents Previous Topic Top Next Topic