473,788 Members | 2,816 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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\nAcce ssing record for "<<queryInput<< "...."<<endl<<e ndl;

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

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

Media::readFrom File("/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.si ze(); i++)
{
Movie *ptr = static_cast<Mov ie *>(mediaItems[i]);
value += ptr->getPrice() * ptr->getNumberInSto ck();
nItems += ptr->getNumberInSto ck();
}

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

// Implement your member function classes here

Movie::Movie()
{

}

void display()
{
}

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

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

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

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

void Media::getData( ifstream& fin)
{

}

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

mediaItems.resi ze(20);

cout<<filename< <endl;

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

while(recordDat a != "ENDOFRECOR DS")
{
int i = 0;

dataBase.getlin e(tempData, 10000);
recordData = tempData;

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

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 displayStockInf o();
int getPrice(){ return price; }
int getNumberInStoc k(){ 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 getDataprotecte d:
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 2620

"acheron05" <ac*******@gmai l.com> wrote in message
news:11******** **************@ d71g2000cwd.goo glegroups.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<Mov ie *> Movies;
Movies.push_bac k( 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::ist ream& input)
{
std::string media_type;
input >> media_type;

if (media_type == "Foreign")
return new Foreign_movie(i nput);

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*******@gmai l.com> wrote in message
news:11******** **************@ y43g2000cwc.goo glegroups.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*******@gmai l.com> wrote in message
news:11******** **************@ y43g2000cwc.goo glegroups.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
15840
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, so I'd like to use an STL container class template such as valarray or vector to represent 1D arrays, and valarrays or vectors of valarrays or vectors to represent 2D arrays. As I said the sizes of the arrays in my intended application are...
7
1926
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 pointer to objects best done like this...with dynamic allocation vector<emp_class*> ptvector; ptvector.push_back(new emp_class(4,"ee")); cout<<ptvector->....
6
2581
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 "SEGV" when run (presumably - attempt to delete deleted memory. Please take a look and see if you can notice any mistakes I'm making. Basically, I want to store classes of my objects in a vector. I also have three further questions:
13
4628
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 is of size 2. How much memory can I save by storing my pointers in c++ arrays, rather than vectors.
4
1755
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 able to strike the puck and move in the direction opposite to which it was struck (a simple collision, basically!)
7
2154
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 * mysprite new sprite(....); when I create a sprite \:
5
1483
by: Sue | last post by:
How can I dynamically allocate vectors of vectors? I need from vector<class1> v1 vector<class1> v2 ... ...
13
2560
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 coords and put all the objects in the same coordinate together.
7
3793
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 dynamic vectors without knowing the size. I want to create a vector which contains a vector of ints: vector<vector<int values; I tried to add the value 35 to the first position of the first vector
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10364
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9967
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6750
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.