<iostream>
// EXAMPLE 1
#include <iostream>
using namespace std;
bool getNumber( int& i )
{
cout << "enter a number ";
char inputString[ 128 ];
cin >> inputString;
i = atoi( inputString );
return true;
}
void main()
{
int number = 0;
getNumber( number );
cout << number << endl;
}
// EXAMPLE 2
#include <iostream>
using namespace std;
bool getNumber( float& f )
{
cout << "enter a floating point number ";
char inputString[ 128 ];
cin >> inputString;
f = atof( inputString );
return true;
}
bool getNumber( int& i )
{
cout << "enter an integer ";
char inputString[ 128 ];
cin >> inputString;
i = atoi( inputString );
return true;
}
bool getNumber( int& i, int& j, int& k )
{
cout << "enter 3 integers ";
char inputString1[ 128 ];
char inputString2[ 128 ];
char inputString3[ 128 ];
cin >> inputString1 >> inputString2 >> inputString3;
i = atoi( inputString1 );
j = atoi( inputString2 );
k = atoi( inputString3 );
return true;
}
void main()
{
int numberI = 0;
float numberF = 0.0f;
int a,b,c;
getNumber( numberI );
getNumber( numberF );
getNumber( a, b, c );
cout << "int number: " << numberI << endl;
cout << "float number: " << numberF << endl;
cout << "three numbers: " << a << " " << b << " " << c << endl;
}
// EXAMPLE 3
#include
using
namespace std;const
int MAX_STRING_LEN = 128;class
CarInfo{
public
: float odometerReading;float lifeTimeServiceCost;
float originalPrice;
char ownerName[MAX_STRING_LEN];
bool isCarALemon();
};
bool
CarInfo::isCarALemon(){
return ( lifeTimeServiceCost > originalPrice );}
void
main(){
CarInfo aCar;
char inputString[MAX_STRING_LEN];cout << "Owner's name: ";
cin >> aCar.ownerName;
cout << "How much did the car cost " << aCar.ownerName << " ?\n$";
cin >> inputString;
aCar.originalPrice = atoi( inputString );
cout << "How much has " << aCar.ownerName << " paid for vehicle service?\n$";
cin >> inputString;
aCar.lifeTimeServiceCost = atoi( inputString );
cout << aCar.ownerName << "'s car is " << ( aCar.isCarALemon() ? "a lemon" : "okay" ) << endl;
}
example 1
<iostream>#include
using
namespace std;class
Student{
private
:long id;
public
:long getID();
void setID( long );
};
long
Student::getID(){
return id;}
void
Student::setID( long inID ){
id = inID;
}
void
main(){
Student student;
student.setID( 1 );
cout << " id: " << student.getID() << endl;
}
example 2
<iostream>#include
using
namespace std;class
Student{
private
: long id;public
:Student();
// default constructorStudent(
int ); // overloaded constructor~Student();
// destructor};
Student::Student()
{
id = 0;
cout << "default constructor called" << endl;
}
Student::Student(
int inID ){
id = inID;
cout << "overloaded constructor called" << endl;
}
Student::~Student()
{
cout << "destructor called ";
cout << "for student: " << id << endl;
}
void
main(){
Student student1;
Student student2( 1 );
cout << "doing stuff" << endl;
}
example 3
<iostream>#include
using
namespace std;class
Student{
private
: long id; bool enrolled;public
: long getID() { return id; }Student& setID(
long id ) { this->id = id; return *this; } bool isEnrolled() { return enrolled; }Student& setEnrolled(
bool enrolled ){
this->enrolled = enrolled; return *this; }};
void
main(){
Student student;
student.setEnrolled(
true ).setID( 1 );}
example 4
<iostream>#include
using
namespace std;// constants
const
int MAX_STRING_LENGTH = 256;const
int MAX_STUDENTS = 20;// class Student interface
class
Student{
private
: static long studentCount;static Student* studentList[ MAX_STUDENTS ];
char name[ MAX_STRING_LENGTH ];
bool enrolled;
long id;
public
:Student(
char*, bool );const char* getName();
void setName( char* );
bool isEnrolled();
void setEnrolled( bool );
long getID();
static Student* getStudentFromID( long id );
static long getStudentCount();
};
// class Student implmentation
Student::Student(
char* name, bool enrolled ){
setName( name );
setEnrolled( enrolled );
id = studentCount;
studentList[ Student::studentCount ] =
this;studentCount++;
}
const
char* Student::getName(){
return name;}
void
Student::setName( char* name ){
strcpy(
this->name, name );}
bool
Student::isEnrolled(){
return enrolled;}
void
Student::setEnrolled( bool enrolled ){
this->enrolled = enrolled;}
long
Student::getID(){
return id;}
// class Student static method implmentation
Student* Student::getStudentFromID(
long id ){
if ( ( id <= studentCount ) && ( id >= 0 ) ){
return studentList[ id ];
}
else
{
return 0;
}
}
long
Student::getStudentCount(){
return studentCount;}
// class Student static member initialization
long
Student::studentCount = 0;Student* Student::studentList[ MAX_STUDENTS ];
// main routine to demonstrate Student
void
main(){
// get students
cout << "Enter student information. Enter name as \"end\" to exit" << endl;
do
{
char name[ MAX_STRING_LENGTH ];
bool enrolled;
cout << "Student name:";
cin >> name;
if ( stricmp( name, "end" ) == 0 )
break;
cout << " enrolled?:";
cin >> enrolled;
new Student( name, enrolled );
}
while( true );
// print list of students
for( int i = 0; i < Student::getStudentCount(); i++ )
{
cout << "Student Record" << endl;
cout << " name: " << Student::getStudentFromID(i)->getName() << endl;
cout << " id: " << Student::getStudentFromID(i)->getID() << endl;
cout << " enrolled:" << Student::getStudentFromID(i)->isEnrolled() << endl;
}
}
example 1 - Better String handling with Methods
<iostream>#include
using
namespace std;const
int MAX_STRING = 256;class
MyString{
private
:char string[ MAX_STRING ];
public
:MyString();
MyString( const char* );
const char* getString();
MyString& setString( const char* );
MyString& appendString( const char* );
bool isEqualTo( const char* );
};
MyString::MyString()
{
string[0] = '\0';
}
MyString::MyString( const char* string )
{
setString( string );
}
const
char* MyString::getString(){
return string;
}
MyString& MyString::setString( const char* string )
{
strcpy( this->string, string );
return *this;
}
MyString& MyString::appendString( const char* string )
{
strcat( this->string, string );
return *this;
}
bool
MyString::isEqualTo( const char* string ){
return ( strcmp( this->string, string ) == 0 );
}
void
main(){
MyString string1( "Hello" );
MyString string2( "Good bye" );
MyString string3;
string3.setString( string1.getString() );
string3.appendString( " and " ).appendString( string2.getString() );
if ( string1.isEqualTo( string2.getString() ) )
{
cout << "string1 == string2" << endl;
}
cout << string3.getString() << endl;
}
example 2 - Overloaded operators in a our Integer class
#include
<iostream>using
namespace std;
class
Integer{
private
:int value;
public
:// Accessor methods
void setValue( int value )
{
this->value = value;
}
int getValue()
{
return value;
}
// Overloaded operators
Integer& operator=( const int setMe )
{
value = setMe;
return *this;
}
Integer operator+( const Integer& addMe )
{
Integer temp;
temp.value = value + addMe.value;
return temp;
}
//Integer& operator+=( const int addMe )
//{
//value = value + addMe;
//return *this;
//}
Integer&
operator+=( const Integer addMe ){
value = value + addMe.value;
return *this;
}
Integer
operator+( const int addMe ){
Integer temp;
temp.value = value + addMe;
return temp;
}
bool operator==( const Integer checkMe )
{
if ( this->value == checkMe.value )
{
return true;
}
else
{
return false;
}
}
bool operator!=( const Integer checkMe )
{
if ( this->value != checkMe.value )
{
return true;
}
else
{
return false;
}
}
// stream operators, declared as friends of class Integer
friend ostream& operator<< ( ostream& out, Integer printMe )
{
out << "Integer is " << printMe.value;
return out;
}
friend istream& operator>> ( istream& in, Integer& getMe )
{
char temp[256];
in >> temp;
getMe.value = atoi( temp );
return in;
}
};
// operator declared as non-member
const
Integer operator+=( Integer& setMe, const int addMe ){
setMe.setValue( setMe.getValue() + addMe );
return setMe;
}
void
main(){
Integer i;
Integer j;
i = 5;
j = i + 10;
i += 20;
cout << "Enter number :";
cin >> i;
cout << "Enter another number:";
cin >> j;
cout << i << " " << j << endl;
if ( i == j )
{
cout << "i == j" << endl;
}
}
example 3 - Even better String handling with operator overloading
#include
<iostream>using
namespace std;const
int MAX_STRING = 256;class
MyString{
private
:char string[ MAX_STRING ];
public
:// constructors
MyString();
MyString(
const char* );// overloaded operators
const MyString& operator= ( const MyString myString );
const MyString& operator= ( const char* string );
MyString
operator+ ( const MyString& myString );MyString
operator+ ( const char* string );const MyString& operator+= ( const MyString myString );
const MyString& operator+= ( const char* string );
bool operator== ( const MyString myString );
friend ostream& operator<< ( ostream& out, MyString myString )
{
return out << myString.string;
}
friend istream& operator>> ( istream& in, MyString& myString )
{
return in >> myString.string;
}
};
MyString::MyString()
{
string[0] = '\0';
}
MyString::MyString(
const char* string ){
strcpy(
this->string, string );}
const
MyString& MyString::operator= ( const MyString myString ){
strcpy(
this->string, myString.string );return *this;
}
const
MyString& MyString::operator= ( const char* string ){
strcpy(
this->string, string );return *this;
}
MyString MyString::
operator+ ( const MyString& myString ){
return MyString( strcat( this->string, myString.string ) );
}
MyString MyString::
operator+ ( const char* string ){
return MyString( strcat( this->string, string ) );
}
const
MyString& MyString::operator+= ( const MyString myString ){
strcat(
this->string, myString.string );return *this;
}
const
MyString& MyString::operator+= ( const char* string ){
strcat(
this->string, string );return *this;
}
bool
MyString::operator== ( const MyString myString ){
return( strcmp( this->string, myString.string ) == 0 );
}
void
main(){
MyString string1;
MyString string2;
cout << "Enter string 1:";
cin >> string1;
cout << "Enter string 2:";
cin >> string2;
if ( string1 == string2 )
{
cout << "string1 == string2" << endl;
}
else
{
cout << "string1 != string2" << endl;
}
string1 = string1 + " " + string2;
cout << string1 << endl;
}
example 1 - Overloading the []
// DEMO - overloaded []
#include <iostream>
using namespace std;
class Integer
{
private:
int value;
char valueString[ 256 ];
int digits;
public:
Integer()
{
setValue( 0 );
}
Integer( int value )
{
setValue( value );
}
Integer& setValue( int value )
{
this->value = value;
itoa( value, this->valueString, 10 );
this->digits = strlen( this->valueString );
return *this;
}
int getDigits()
{
return digits;
}
Integer& operator=( int value )
{
setValue( value );
}
int operator[]( int index )
{
if ( index > ( digits - 1 ) )
{
index = digits - 1;
}
if ( index < 0 )
{
index = 0;
}
return valueString[ index ] - 48;
}
};
void main()
{
Integer integer( 459874 );
for ( int i = 0; i < integer.getDigits(); i++ )
{
cout << "digit " << i << " = " << integer[i] << endl;
}
}
example 2 - Overloading the ++
// DEMO - overloaded ++
#include <iostream>
using namespace std;
class Integer
{
private:
int value;
public:
Integer& operator=( int value )
{
this->value = value;
return *this;
}
Integer& operator++()
{
this->value++;
return *this;
}
Integer operator++( int )
{
Integer temp = *this;
this->value++;
return temp;
}
friend ostream& operator<< ( ostream& out, Integer printMe )
{
out << "Integer is " << printMe.value;
return out;
}
};
void main()
{
Integer integer;
integer = 12;
cout << integer++ << endl;
cout << ++integer << endl;
}
example 3 - Standard Library - string class
// DEMO - string
#include <iostream>
#include <string>
using namespace std;
// basic string parsing demo
void main()
{
string inputString;
// user enters a string
cout << "Enter a string:";
cin >> inputString;
// split string at comma character
long splitAt;
// find the position of the first comma
while( ( splitAt = inputString.find_first_of( ',' ) ) != string::npos )
{
// split off the first word seperated by a comma
string temp = inputString.substr( 0, splitAt );
// remove this first word from the input string
inputString = inputString.substr( splitAt + 1, inputString.length() - splitAt - 1 );
// print out the split off word
cout << temp << endl;
}
// print what is left of the string
cout << inputString;
}
example 4 - Standard Library - string class 2
// DEMO - string 2, operators
#include <iostream>
#include <string>
using namespace std;
// basic string parsing demo
void main()
{
string inputString1;
string inputString2;
string combinedString;
// user enters a string
cout << "Enter word 1:"; cin >> inputString1;
cout << "Enter word 2:"; cin >> inputString2;
// overloaded string == operator
if ( inputString1 == "hello" )
{
cout << "aloha" << endl;
}
// overloaded string = and + operators
combinedString = inputString1 + " " + inputString2;
// print the combined string
cout << combinedString << endl;
}
example 5 - Standard Library - vector 1
// DEMO - vector with numeric
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// basic string parsing demo
void main()
{
vector<int> arrayOfInts;
string inputString;
cout << "Enter numbers (enter \"end\" to stop)" << endl;
while ( true )
{
cin >> inputString;
if ( inputString == "end" )
break;
arrayOfInts.push_back( atoi( inputString.c_str() ) );
}
for ( int i = 0; i < arrayOfInts.size(); i++ )
{
cout << arrayOfInts[ i ] << " ";
}
cout << endl;
}
example 6 - Standard Library - vector 2
// DEMO - vector with numeric and algorithm
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void getList( vector<int>& ints )
{
string inputString;
cout << "Enter numbers "
<< "(enter \"end\""
<< "to stop)" << endl;
while ( true )
{
cin >> inputString;
if ( inputString == "end" )
break;
ints.push_back( atoi( inputString.c_str() ) );
}
}
void printList( vector<int> ints )
{
for ( int i = 0; i < ints.size(); i++ )
{
cout << ints[ i ] << " ";
}
cout << endl;
}
// basic string parsing demo
void main()
{
vector<int> arrayOfInts;
getList( arrayOfInts );
cout << "sorted" << endl;
sort( arrayOfInts.begin(), arrayOfInts.end() );
printList( arrayOfInts );
cout << "shuffled" << endl;
random_shuffle( arrayOfInts.begin(), arrayOfInts.end() );
printList( arrayOfInts );
}
example 7 - Standard Library - vector 3
// DEMO - vector with string and algorithm
#pragma warning(disable:4786)
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void getList( vector<string>& stringVect )
{
string inputString;
cout << "Enter words (enter \"end\" to stop)" << endl;
while ( true )
{
cin >> inputString;
if ( inputString == "end" )
break;
stringVect.push_back( inputString );
}
}
void printList( vector<string> stringVect )
{
for ( int i = 0; i < stringVect.size(); i++ )
{
cout << stringVect[ i ] << " ";
}
cout << endl;
}
// basic string parsing demo
void main()
{
vector<string> arrayOfStrings;
getList( arrayOfStrings );
cout << "sorted" << endl;
sort( arrayOfStrings.begin(), arrayOfStrings.end() );
printList( arrayOfStrings );
cout << "shuffled" << endl;
random_shuffle( arrayOfStrings.begin(), arrayOfStrings.end() );
printList( arrayOfStrings );
}
example 1
// Basic Inheritance
#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
string name;
string sound;
};
class Dog : public Animal
{
public:
Dog()
{
name = "Dog";
sound = "Bark";
}
};
class Cat : public Animal
{
public:
Cat()
{
name = "Cat";
sound = "Meow";
}
};
void main()
{
Dog dog;
Cat cat;
cout << dog.name << endl;
cout << cat.name << endl;
}
example 2
// Protected members
#include <iostream>
#include <string>
using namespace std;
class Animal
{
private:
int count;
protected:
string name;
string sound;
public:
string getName() { return this->name; }
};
class Dog : public Animal
{
public:
Dog()
{
name = "Dog";
sound = "Bark";
}
};
void main()
{
Dog dog;
//cout << dog.name << endl;
cout << dog.getName() << endl;
}
example 3
// Access modifiers
#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
string name;
string sound;
};
class Dog : private Animal
{
public:
using Animal::name;
Dog()
{
name = "Dog";
sound = "Bark";
}
};
void main()
{
Dog dog;
cout << dog.name << endl;
}
example 4
// Overriding
#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
string name;
void produceSound() { cout << "no sound defined\n"; }
};
class Dog : public Animal
{
public:
Dog() { name = "Dog"; }
void produceSound() { cout << "woof\n"; }
};
class Cat : public Animal
{
public:
Cat() { name = "Cat"; }
};
void main()
{
Dog dog;
Cat cat;
dog.produceSound();
cat.produceSound();
}
example 5
// Pure Virtual
#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
string name;
virtual void produceSound() = 0;
};
class Dog : public Animal
{
public:
Dog() { name = "Dog"; }
void produceSound()
{
cout << "woof\n";
}
};
class Cat : public Animal
{
public:
Cat() { name = "Cat"; }
void produceSound()
{
cout << "meow\n";
}
};
void main()
{
Dog dog;
Cat cat;
dog.produceSound();
cat.produceSound();
}
example 6
// Multiple Inheritance
#include <iostream>
#include <string>
using namespace std;
class Animal
{
protected:
string name;
public:
virtual void produceSound() = 0;
};
class Dog : public Animal
{
public:
Dog() { name = "Dog"; }
void produceSound()
{
cout << "woof\n";
}
};
class Employee : public Animal
{
public:
float salary;
void produceSound()
{
cout << "let's have a meeting\n";
}
};
class PoliceDog :
public Dog,
public Employee
{
public:
void heal() { };
void attack() { cout << "attack\n"; };
using Dog::produceSound;
};
void main()
{
PoliceDog policeDog;
policeDog.produceSound();
policeDog.attack();
}
example 1
// Simple Polymorphism
#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
string name;
virtual void produceSound() = 0;
};
class Dog : public Animal
{
public:
Dog() { name = "Dog"; }
void produceSound()
{
cout << "woof\n";
}
};
class Cat : public Animal
{
public:
Cat() { name = "Cat"; }
void produceSound()
{
cout << "meow\n";
}
};
void main()
{
Animal* animals[2];
animals[0] = new Dog();
animals[1] = new Cat();
for( int i = 0; i < 2; i++ )
{
animals[i]->produceSound();
}
}
example 2
// Polymorphism 2
#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
string name;
virtual void produceSound() = 0;
};
class Dog : public Animal
{
public:
Dog() { name = "Dog"; }
void produceSound() { cout << "woof\n"; }
};
class Cat : public Animal
{
public:
Cat() { name = "Cat"; }
void produceSound() { cout << "meow\n"; }
void scratch() { cout << "scratch\n"; }
};
void main()
{
Animal* animals[2];
animals[0] = new Dog();
animals[1] = new Cat();
animals[1]->scratch();
for( int i = 0; i < 2; i++ )
{
animals[i]->produceSound();
}
}
example 3
// Polymorphism - typeid
#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
string name;
virtual void produceSound() { cout << "no sound defined\n"; }
};
class Dog : public Animal
{
public:
Dog() { name = "Dog"; }
void produceSound() { cout << "woof\n"; }
};
class Cat : public Animal
{
public:
Cat() { name = "Cat"; }
};
void main()
{
Animal* animals[2];
animals[0] = new Dog();
animals[1] = new Cat();
for( int i = 0; i < 2; i++ )
{
cout << typeid( *animals[i] ).name() << " says ";
animals[i]->produceSound();
}
}
example 4
// Polymorphism - typeid and dynamic_cast
#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
string name;
virtual void produceSound() { cout << "no sound defined\n"; }
};
class Dog : public Animal
{
public:
Dog() { name = "Dog"; }
void produceSound() { cout << "woof\n"; }
};
class Cat : public Animal
{
public:
Cat() { name = "Cat"; }
void scratch() { cout << "scratch\n"; }
};
void main()
{
Animal* animals[2];
animals[0] = new Dog();
animals[1] = new Cat();
for( int i = 0; i < 2; i++ )
{
cout << typeid( *animals[i] ).name() << " says ";
animals[i]->produceSound();
if ( typeid( *animals[i] ) == typeid( Cat ) )
{
dynamic_cast< Cat* >(animals[i])->scratch();
}
}
}
example 5
// Simple Class Template with parameter
#include <iostream>
#include <string>
using namespace std;
template < typename SomeType, int size >
class Stack
{
private:
SomeType data[ size ];
int index;
public:
Stack() { index = 0; }
void putItemInList( SomeType item )
{
if ( index < size )
data[ index++ ] = item;
}
SomeType popItemFromList()
{
if ( index > 0 )
{
return data[ --index ];
}
return data[0];
}
bool empty()
{
return( index == 0 );
}
};
int main()
{
Stack< int, 10 > myIntStack;
Stack< string, 10 > myStringStack;
myIntStack.putItemInList( 1 );
myIntStack.putItemInList( 2 );
myIntStack.putItemInList( 3 );
while ( myIntStack.empty() == false )
cout << myIntStack.popItemFromList()
<< endl;
myStringStack.putItemInList( "Once" );
myStringStack.putItemInList( "there" );
myStringStack.putItemInList( "was" );
while ( myStringStack.empty() == false )
cout << myStringStack.popItemFromList()
<< endl;
return 0;
}
example 6
// More Advanced Class Template
#pragma warning(disable:4786)
#include <iostream>
#include <time.h>
#include <string>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
template < class T >
class RandomDataPopper
{
private:
vector< T > data;
T returnMe;
public:
RandomDataPopper()
{
srand( (unsigned)time( NULL ) );
}
static int random(int n)
{
return rand() % n;
}
void addElement( T element )
{
data.push_back( element );
random_shuffle( data.begin(), data.end(),
pointer_to_unary_function< int, int >(random) );
}
bool popElement( T& returnMe )
{
if ( data.size() > 0 )
{
returnMe = data[0];
data.erase( data.begin() );
return true;
}
else
{
return false;
}
}
long size()
{
return ( data.size() );
}
};
void main()
{
RandomDataPopper<string> stringPopper;
stringPopper.addElement( string("Hello World!") );
stringPopper.addElement( string("Once upon a midnight dreary") );
stringPopper.addElement( string("640KB should be enough") );
stringPopper.addElement( string("I am the one") );
string output;
while( stringPopper.popElement( output ) )
{
cout << output << endl;
}
}
example 7
// Streams - Console
#include <iostream>
#include <string>
using namespace std;
const int MAX_STRING = 10;
int main()
{
cout << "Please enter some characters:" << endl;
// let's take a look at the cin buffer without affecting it
char input = cin.peek();
if ( input > '0' && input < '9' )
{
string input;
cin >> input;
int i = atoi(input.c_str());
cout << "Number: " << i << endl;
}
else
{
char input[ MAX_STRING ];
cin.get( input, MAX_STRING );
cout << "Text: " << input << endl;
}
return 0;
}
example 8
// Streams - File I/O
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// file output
ofstream myOutputFile( "file.test" );
myOutputFile << "Hello, this a file" << endl;
myOutputFile.close();
// file input
ifstream myInputFile( "file.test" );
cout << "my input file contains:\n" << myInputFile.rdbuf();
myInputFile.close();
return 0;
}
example 9
// Exceptions
#include <iostream>
using namespace std;
float divide( int a, int b )
{
if ( b != 0 )
return ( a / b );
else
return 0;
}
float divide2( int a, int b )
{
try
{
return ( a / b );
}
catch ( ... )
{
cout << "Error!" << endl;
return 0;
}
}
int main()
{
divide2( 5, 0 );
return 0;
}