[try Beta version]
Not logged in

 
Virtual Functions!

Apr 13, 2014 at 11:59pm
I'm writing a program that calculate the carbon footprint for car, building, and bicycle. i have three classes building, car, bicycle. class called carbonfootprint have the pure virtual and should have the formula, but i didn't find it. having a little bit hard understanding some requests. like,

• Write an abstract class CarbonFootprint with only a pure virtual getCarbonFootprint
method. Have each of your classes inherit from that abstract class and implement the getCarbonFootprint method to calculate an appropriate carbon footprint for that class.
• The main() function in the given program creates objects of each of the three classes, places
pointers to those objects in a vector of CarbonFootprint pointers. You need to iterate through
the vector, polymorphically invoking each object’s getCarbonFootprint method.

// Homework09P02.cpp
// Test program for CarbonFootprint and implementing classes.
#include <iostream>
#include <vector>
using namespace std;

int main()
{

vector< CarbonFootprint* > list;

// add elements to list
list.push_back( new Bicycle() );
list.push_back( new Building( 2500 ) );
list.push_back( new Car( 10 ) );

// display carbon footprint of each object
for ( size_t i = 0; i < list.size(); ++i ){
//TODO: polymorphically invoking each object¡¯s getCarbonFootprint method

}

// release elements of list
for ( size_t i = 0; i < list.size(); ++i ){
//TODO: release elements in the list
CarbonFootprint* ptr;
delete ptr;
}

} // end main

class Building
{};

class Car
{};

class Bicycle
{};

class CarbonFootprint
{
protected:

public:

virtual void getCarbonFootprint() = 0;

void getCarbonFootprint()
{

}
};
Last edited on Apr 14, 2014 at 12:12am
Apr 14, 2014 at 4:34am
Start doing it step by step: Now you are at "Have each of your classes inherit from that abstract class". WQhat problems do you have with this?
Apr 15, 2014 at 1:23am
ok gd, i'll work on it again.
Apr 15, 2014 at 4:48am
"Polymorphically invoking each object's getCarbonFootprint() method" simply means to call the getCarbonFootprint() method. :)

Joe
Apr 15, 2014 at 5:13am
Refer to http://www.cplusplus.com/doc/tutorial/polymorphism/. Given examples in this page is simple enough and it replicates your problem statement.

Topic archived. No new replies allowed.