A second situation in which a class may refer to iself occurs when a
method of a class returns an instance of that class as a result. Some
examples of methods that return objects in their own class are the
following:
The File class is extended to add a method to perform the copying operations described above. The extended definition is:
class File { // Version 2
private:
// encapsulated implementation goes here
public:
File(char* fileName); // represents file with given name
File(); // unknown, as yet, file
char* Name(); // reply name of file
int Exists(); // does file Exist?
void View(); // scrollable view window
void Edit(char* editor); // edit file using "editor"
void Delete(); // delete file
void CopyTo(File& other); // copy me to other
void CopyFrom(File& other); // copy other to me
~File(); // free name
};
In this revised version of the File class, the CopyTo and CopyFrom methods
take as their input arguments references to other File objects to which the
called object copies itself to or from. This class can be used in the following
way:
FileNavigator nav; File sourceFile = nav.AskUser(); File targetFile = nav.AskUser(); sourceFile.CopyTo(targetFile); sourceFile.View(); targetFile.View();In this example the user is asked to select two existing files. The file first selected is copied to the second file. The two viewing windows that are created can be used to visually confirm that the files are identical.
As noted in the examples above, it is also useful for an operation of a class
to return an object of that same class. This is illustrated by the following
revisions to the Location and Shape classes:
class Location { // Version 2
private:
// encapsulated implementation goes here
public:
Location(int x, int y); // specific location
Location(); // default location
int Xcoord(); // return x-axis coordinate
int Ycoord(); // return y-axis coordinate
Location Xmove(int amount); // move right/left
Location Ymove(int amount); // move up/down
};
class Shape { // Version 2
private:
// encapsulated implementation goes here
public:
Shape(int width, int height);// specific shape
Shape(); // default shape
int Height(); // return height
int Width(); // return width
Shape Resize(float factor); // return adjusted shape
};
Frame window(nearTop, largeSquare); Shape currentShape = window.WhatShape(); Location currentLocation = window.WhereAt(); Shape newShape = currentShape.Resize(0.9); Location newLocation = currentLocation.Xmove(50); window.MoveTo( newLocation ); window.Resize( newShape );