Skip to content

Instantly share code, notes, and snippets.

@natemcmaster
Created September 21, 2013 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natemcmaster/6654001 to your computer and use it in GitHub Desktop.
Save natemcmaster/6654001 to your computer and use it in GitHub Desktop.
Sample of inheritance and vectors.
/*
* Fruit.cpp
*
* Created on: Sep 21, 2013
* Author: nmcmaster
*/
#include "Fruit.h"
using namespace std;
Fruit::Fruit(string newName){
this->name=newName;
}
string Fruit::getName(){
return this->name;
}
/*
* Fruit.h
*
* Created on: Sep 21, 2013
* Author: nmcmaster
*/
#pragma once
#include <string>
using namespace std;
class Fruit{
private:
string name;
public:
Fruit(string);
string getName();
};
#include "Kiwi.h"
Kiwi::Kiwi (string NextName, int newsize) :Fruit(NextName) {
this->size = newsize;
}
int Kiwi::getSize(){
return this->size;
}
#pragma once
#include "Fruit.h"
class Kiwi : public Fruit{
private:
int size;
public:
Kiwi(string,int);
int getSize();
};
/*
* main.cpp
*
* Created on: Sep 21, 2013
* Author: nmcmaster
*/
#include <iostream>
#include "Fruit.h"
#include "Kiwi.h"
#include <vector>
using namespace std;
int main(){
string apple("Gala Apple");
Fruit fruit1("banana");
Fruit fruit2(apple);
Kiwi fruit3("brown", 8);
cout << fruit1.getName() <<endl;
cout << fruit2.getName() << endl;
cout << fruit3.getName() << ' ' << fruit3.getSize() << endl;
cout<<endl;
cout << "### Vector Demo ### "<<endl;
cout<<"How many fruit?"<<endl;
int howMany;
cin>>howMany;
vector<Kiwi> manyFruits;
for(int i=0; i < howMany ; i ++){
Kiwi newFruit("new fruit name",i+24);
manyFruits.push_back(newFruit);
}
/* Print out everything in a vector */
vector<Kiwi>::iterator it=manyFruits.begin();
while(it != manyFruits.end()){
cout<< it->getName() << " " << it->getSize() << endl;
it++;
}
cout<<"The second fruit is ...."<<endl;
Kiwi secondFruit=manyFruits.at(1);
cout<<secondFruit.getName()<< " " << secondFruit.getSize() <<endl;
cout<<"Now we assign the third fruit spot to a new kiwi, size 189"<<endl;
Kiwi bigFruit("Big Fruit",189);
manyFruits[2]=bigFruit;
cout<<"The third fruit is ...."<<endl;
Kiwi thirdFruit=manyFruits.at(2);
cout<<thirdFruit.getName()<< " " << thirdFruit.getSize() <<endl;
cout<<" The print out, one more time "<<endl;
it=manyFruits.begin();
while(it != manyFruits.end()){
cout<< it->getName() << " " << it->getSize() << endl;
it++;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment