Last active
December 16, 2015 18:09
-
-
Save danamuise/5476172 to your computer and use it in GitHub Desktop.
C++ Class example: Overloaded Constructor, member function defined outside of the class, an object deifined with default constructor.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
class Distance | |
{ | |
public: | |
//Overloaded constructor example | |
//constructor with no args (default values) | |
Distance() : feet(0), inches(0.0) | |
{} | |
//constructor with two args | |
Distance (int ft, float in) : feet(ft), inches(in) | |
{} | |
void getdist() | |
{ | |
cout << "Enter feet: "; | |
cin >> feet; | |
cout << "Enter inches: "; | |
cin >> inches; | |
} | |
void showdist() | |
{ | |
cout << feet << "\'-" << inches << '\"'; | |
} | |
void add_dist(Distance, Distance); //declaration of a MEMBER FUNCTION | |
private: | |
int feet; | |
float inches; | |
}; | |
//************************************************ | |
// Definition of a MEMBER FUNCTION, outside the class | |
void Distance::add_dist(Distance d2, Distance d3) | |
{ | |
inches=d2.inches + d3.inches; | |
feet =0; | |
if (inches >=12) | |
{ | |
inches-= 12.0; //decrease inches by 12 | |
feet++; | |
} | |
feet+= d2.feet + d3.feet; //increase feet by (d2.feet + d3.feet) | |
} | |
int main() | |
{ | |
Distance dist1, dist3; //create two objects of the Distance class | |
Distance dist2(11, 6.25);//create one object, defined | |
dist1.getdist(); | |
dist3.add_dist(dist1, dist2); | |
cout << "\ndist1 = "; dist1.showdist(); | |
cout << "\ndist2 = "; dist2.showdist(); | |
cout << "\ndist3 = "; dist3.showdist(); | |
cout << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment