C++: Reusing a method

This entry is part 29 of 61 in the series C++

The original designer of C++ reasoned that OOP is well suited for building large scale project.

Some of the core ideas of OOP such as encapsulation and inheritance are all meant to make it easy for us to build large program and to reuse the code we have built.

This example shows how the same method is used.  We actually need to create a second instance to hold the data and to call the method under this second instance.

#include <iostream>
#include <string>

using namespace std;

class Rock

	string name;
	string track;

	int Display();

	Rock(string, string);  //This is the constructor
	~Rock();  //This is the destructor


int Rock::Display()

	cout << "This is " << name << " Singing " << track;
	cout << endl;

	return 0;

Rock::Rock(string name2, string track2)
	name = name2;
	track = track2;

	cout << "And This Is The End";
	cout << endl;

int main()

	string name1 = "Rod Stewart";
	string track1 = "I was only Joking";

	Rock rockstar(name1,track1); // instance declaration

	string name2 = "Metallica";
	string track2 = "Enter The Sandman";

	Rock rockstar2(name2, track2); // instance declaration

	return 0;



Series Navigation<< C++: Implementing a method
C++: Creating an object >>