473,395 Members | 1,756 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Help with Vectors and Dynamic Objects

Hi there,

Hopefully I won't fit the stereotype of the typical student posting his
assignment to be written for him, but I am quite stuck. If anyone could
give me some help in how to create dynamic objects (which inherit from
a base class) and storing them in a vector, it would be absolutely
wonderful at this point. I think from there I might be able to sculpt
the rest of the program without (too much) trouble. I'll post what I've
been trying to do so far and also the header file.

Thanks in advance for any help.

#include "a3.h"

string queryInput;

// Don't forget to supply your information in the function below . . .
void displayInfo()
{
cout << "----------------------------------------" << endl;
cout << "Assignment 3 Semester 1 2006" << endl;
cout << " Submitted by: Donald, Duck, 00000000" << endl;

cout << "----------------------------------------" << endl;
cout << endl << queryInput << endl;
}

//Driver for the Media/Movie classes for assignment 3,
//2006, Semester 1
int main()
{

cout<<"Media Database Control Program v0.4b\n\n"<<
"Please enter the title of the media record you wish to view: ";
getline(cin, queryInput);
cout<<"\n\nAccessing record for "<<queryInput<<"...."<<endl<<endl;

// Call the global function to print Student/Group names and IDs
displayInfo();

// Container of Media pointers
vector<Media *> mediaItems;

Media::readFromFile("/a3-input.txt", mediaItems);

// Display to the screen
for(unsigned i = 0; i < mediaItems.size(); i++)
{
mediaItems[i]->display(); // use the polymorphic display function
cout<<endl;
}

// Work out total stock value, StockInfo functions are inaccessible
// unless we recast
int value = 0;
int nItems = 0;

for(unsigned i=0; i<mediaItems.size(); i++)
{
Movie *ptr = static_cast<Movie *>(mediaItems[i]);
value += ptr->getPrice() * ptr->getNumberInStock();
nItems += ptr->getNumberInStock();
}

cout << "Total stock value of " << nItems << " items is " << value <<
endl;
return 0;
}

// Implement your member function classes here

Movie::Movie()
{

}

void display()
{
}

void Movie::setDirector(const string& d)
{
director = d;
}

void Movie::setTime(int t)
{
time = t;
}

void Movie::setQuality(int q)
{
quality = q;
}

void Media::setTitle(const string& t)
{
title = t;
}

void Media::getData(ifstream& fin)
{

}

void Media::readFromFile(const string& filename, vector<Media*>&
mediaItems)
{

mediaItems.resize(20);

cout<<filename<<endl;

char tempData[10000];
string recordData;
ifstream dataBase("/a3-input.txt");

while(recordData != "ENDOFRECORDS")
{
int i = 0;

dataBase.getline(tempData, 10000);
recordData = tempData;

if(recordData == "Movie")
{
Movie* mediaItems[i];
mediaItems[i].setDirector(recordData);

i++;
}
}

dataBase.close();
}
Here is the header file....

/* Assignment A3, Header file, See A3.doc for specification.
*
* Class Hierarchy:
*
* Media StockItem
* | |
* +--------------------------+
* |
* V
* Movie
* |
* V
* +------------+-------------+
* | |
* V V
* Revised Foreign
*
*
* *** DO NOT CHANGE THIS FILE ***
*/

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

// Base class to provide stock control info
class StockItem{
public:
void readStockInfo( ifstream& fin ); // read in price and
numberInStock
void displayStockInfo();
int getPrice(){ return price; }
int getNumberInStock(){ return numberInStock; }
protected:
int price; // in cents
int numberInStock;
};

// Abstract base class for all media products
class Media{
public:
virtual ~Media(){}
virtual void getData( ifstream& fin) = 0; // get a single record
virtual void display() = 0; // print out to cout the details of a
record

void setTitle( const string& t);

// Open stated file, and read in records into the vector of Media
// pointers (which is passed by reference) allocating a new object
// of the right type, dynamically, to the i'th pointer
static void readFromFile( const string& filename, vector<Media*>& m);
protected:
string title;
};

// Declaration/definition of Movie
class Movie : public Media, public StockItem{
public:
Movie();
void setDirector( const string& d );
void setTime( int t = 0);
void setQuality( int q = 0 );

virtual void display(); // print out to cout the details of a
record
virtual void getData( ifstream& fin); // get a single record

protected:
string director;
int time; // in minutes
int quality; // 0 (bad) to 4 (excellent)

// These are optional but allow code reuse for polymorphs display
// and getDataprotected:
void commonDisplay();
void getCommonData( ifstream& fin);

};

// Declaration of Foreign
class Foreign : public Movie {
public:
void setLanguage( const string& lang );
virtual void display(); // see descriptions in Movie
virtual void getData( ifstream& fin);
private:
string language; // language of a foreign film
};

// Declaration of Revised
class Revised : public Movie{
public:
void setRevisedTime( int rt = 0);
void setChanges( const string& ch );
virtual void display(); // see descriptions in Movie
virtual void getData( ifstream& fin);
private:
int revisedTime; // the revised running time in minutes
string changes; // description of any changes made
};

May 14 '06 #1
8 2572

"acheron05" <ac*******@gmail.com> wrote in message
news:11**********************@d71g2000cwd.googlegr oups.com...
Hi there,

Hopefully I won't fit the stereotype of the typical student posting his
assignment to be written for him, but I am quite stuck. If anyone could
give me some help in how to create dynamic objects (which inherit from
a base class) and storing them in a vector, it would be absolutely
wonderful at this point. I think from there I might be able to sculpt
the rest of the program without (too much) trouble. I'll post what I've
been trying to do so far and also the header file.

It's generally considered bad practice to store raw pointers in a vector (or
most any container for that matter), though I suppose in the context of a
beginning C++ class it's not completely unreasonable.
To create a "dynamic" object, use the 'new' operator:

Movie *pMovie = new Movie; // create a "Movie" object and assign its
pointer to 'pMovie'
Storing objects in a vector is typically done using vector's 'push_back'
member function:

std::vector<Movie *> Movies;
Movies.push_back( pMovie ); // add the 'pMovie' pointer to the vector

This should be enough to get you started.

- Dennis
May 14 '06 #2
Not that your code is poor but can't you at least indicate which line
your problem is? Certainly you don't want us to guess your problem.

Or even better, just post the relevant bit to demonstrate what you want
to do.

Remember, the purpose of your post is to help us help yourself.

Regards,
Ben
May 14 '06 #3
Yep, sorry about that... Heres my basic overview:

The program reads in an input file of Media records and creates
specific objects for each of these 4-6 line records, based on their
type. For example, If a string is read from the input file and matches
"Movie" then create a new dynamic object "Movie" which inherits
properties from the base class "Media". Same for "Foreign" and
"Revised" types of records aswell. Pointers to these objects (as per
this assignment's specification) then need to be stored within the
container:

vector<Media *> mediaItems;

I have the infrastructure in place to cycle through the input
"database" and read in the lines of text, plus the flow control to
distinguish between the different types of records. I'm just not sure
how to create new objects of the given type and store pointers to them
within the vector. I'm also not sure how the vector gets passed back to
the calling function either.

Hopefully this will make a bit more sense! Thanks very much.

May 14 '06 #4
acheron05 wrote:
Yep, sorry about that... Heres my basic overview:

The program reads in an input file of Media records and creates
specific objects for each of these 4-6 line records, based on their
type. For example, If a string is read from the input file and matches
"Movie" then create a new dynamic object "Movie" which inherits
properties from the base class "Media". Same for "Foreign" and
"Revised" types of records aswell. Pointers to these objects (as per
this assignment's specification) then need to be stored within the
container:

vector<Media *> mediaItems;


Aha, this information makes it all clearer doesn't it?

Here I provide a simple function from which you can build your solution
upon:

Media* get_media_from_stream(std::istream& input)
{
std::string media_type;
input >> media_type;

if (media_type == "Foreign")
return new Foreign_movie(input);

if (media_type == "Movie")
return new Movie(input);

// ...

return 0;
}

Notice that you need to design a constructor for the media types so that
they can take an istream as argument.

Regards,
Ben
May 14 '06 #5
I've implemented my code to create new objects for the readFromFile
member function, but am now getting an error message come up:

Undefined symbols:
vtable for Movie

Is this due to the virtual functions within the Media and Movie classes
and incorrect constructors?

Thanks again

May 16 '06 #6
Do you have deconstructors defined for your classes?

That usually is what my problem is if I get an undefined vtable error.

Gemma

"acheron05" <ac*******@gmail.com> wrote in message
news:11**********************@y43g2000cwc.googlegr oups.com...
I've implemented my code to create new objects for the readFromFile
member function, but am now getting an error message come up:

Undefined symbols:
vtable for Movie

Is this due to the virtual functions within the Media and Movie classes
and incorrect constructors?

Thanks again

May 18 '06 #7
Gemma Fletcher wrote:
"acheron05" <ac*******@gmail.com> wrote in message
news:11**********************@y43g2000cwc.googlegr oups.com...
I've implemented my code to create new objects for the readFromFile
member function, but am now getting an error message come up:

Undefined symbols:
vtable for Movie

Is this due to the virtual functions within the Media and Movie classes
and incorrect constructors?


Do you have deconstructors defined for your classes?
That usually is what my problem is if I get an undefined vtable error.


Gemma,
Please learn to quote correctly on Usenet. See
http://en.wikipedia.org/wiki/Top-post for more informations. And it's
"destructor", not "deconstructor".

Acheron05 (OP),
Always check the FAQ before posting. You'd be surprised.
http://www.parashift.com/c++-faq-lit...html#faq-23.10
Jonathan

May 18 '06 #8
<Snip>

Do you have deconstructors defined for your classes?
That usually is what my problem is if I get an undefined vtable error.


Gemma,
Please learn to quote correctly on Usenet. See
http://en.wikipedia.org/wiki/Top-post for more informations. And it's
"destructor", not "deconstructor".

Acheron05 (OP),
Always check the FAQ before posting. You'd be surprised.
http://www.parashift.com/c++-faq-lit...html#faq-23.10
Jonathan


Jonathan,

Yes, I unfortunately posted this before the top-posting problem was brought
to my attention in another thread :)

Won't happen again.

Not sure why I said deconstructors - it was late. *blush*
Gemma
May 19 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Michael Aramini | last post by:
I need to represent 1D and 2D arrays of numeric or bool types in a C++ program. The sizes of the arrays in my intended application are dynamic in the sense that they are not known at compile time,...
7
by: john townsley | last post by:
when using vectors with pointers of objects. is it best to create instances then point to them or dynamic allocation upon creating a vector element. I can do this, but is creating a vector with...
6
by: Alfonso Morra | last post by:
I have written the following code, to test the concept of storing objects in a vector. I encounter two run time errors: 1). myClass gets destructed when pushed onto the vector 2). Prog throws a...
13
by: Ben | last post by:
I have a program which is using a lot of memory. At the moment I store a lot of pointers to objects in std::vector. (millions of them) I have three questions: 1) Lets say the average Vector...
4
by: Brian Basquille | last post by:
Hello all, Well, we've gotten to it: the real meaty area of my Air Hockey game.. Any help or suggestions for the following would be much appreciated. In plain terms: My paddle needs to be...
7
by: enki | last post by:
What I want to do is create sprites and put them in a vector. I know that this specific example dosn't realy fit in this group but my sprite are ponters. vector<*sprite>spvec; sprite *...
5
by: Sue | last post by:
How can I dynamically allocate vectors of vectors? I need from vector<class1> v1 vector<class1> v2 ... ...
13
by: JoeC | last post by:
I am completly lost. I would like to create a function that takes two vectors. These two vectors have objects with x and y coords, what I want to do find all the objects in the same x and y...
7
by: Markus Pitha | last post by:
Hello again, I have another question about the handling of multidimensional vectors. Actually, it's not difficult when the size is known at the beginning, but I still wasn't able to create...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.