Let’s take a look at constructor overloading, objects as function arguments, and returning objects from functions.
CDistance.h
#ifndef CDISTANCE_H #define CDISTANCE_H class CDistance { public: CDistance() : _meters(0), _centimeters(0.0) {} CDistance(int meters, double centimeters) : _meters(meters), _centimeters(centimeters) {} void getDist(); void showDist(); voidd addDist(CDistance a, CDistance b); private: int _meters; double _centimeters; }; #endif // CDISTANCE_H
Our overloaded constructors use initialization lists to specify what we want to set the member variables to.
The scope resolution operator, ::, is used to specify what class something is associated with. We use the scope resolution operator when defining member functions outside the class declaration.
CDistance.cpp
#include "CDistance.h" #include <iostream> void CDistance::getDist() { std::cout << "Please enter meters: "; std::cin >> _meters; std::cout << "Please enter centimeters: "; std::cin >> _centimeters; } void CDistance::showDist(){ std::cout << _meters << " m " << _centimeters << " cm "; } void CDistance::addDist(CDistance a, CDistance b){ _centimeters = a._centimeters + b._centimeters; _meters = 0; if(_centimeters >= 100){ _centimeters -= 100; _meters++; } _meters += a._meters + b._meters; }
The syntax for function parameters that are objects is the same as that for arguments are are simple times such as int or char.
A special example of passing in an object as an argument is the default copy constructor. The default copy constructor performs a member-wise copy of one object’s values to another.
#include "CDistance.h" using namespace std; int main() { CDistance dOne; CDistance dTwo(5, 50); CDistance dThree; cout << "First Distance: " ; dOne.showDist(); cout << endl; cout << "Second Distance: " ; dTwo.showDist(); cout << endl; //default copy constructor dOne = dTwo; dThree.addDist(dOne, dTwo); dTwo.addDist(dOne, dThree); cout << "First Distance: " ; dOne.showDist(); cout << endl; cout << "Second Distance: " ; dTwo.showDist(); cout << endl; cout << "Third Distance: " ; dThree.showDist(); cout << endl; return 0; }