473,625 Members | 2,690 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

noobs and pointers


Hi,

I am a noob. I am trying to store Student objects pointers, in a
vector, within a School object.
I call a setter function to add the pointer. If I use this method it
works,
Student st = Student("Randy" );
Student * stp = & st;
sc.addStudent(s tp);

My problem is passing a Student to the School function. I have an
overridden function. I try to create a pointer from the passed
Student. I bet that's my problem because it's a copy ?

This all came about because I want to have a more succinct method for
doing this, just like the big kids do:
Student st = Student("Randy" );
Student * stp = & st;
sc.addStudent(s tp);

I've read lots but am apperantly missing the point. I am referencing
the C++ Primer.
here's my output too ... 2 Bills ?? ahaha ...

Schools Constructor 1
Student Constructor2 Randy
Overload addStudent1()
Student Constructor2 Biff
Overload addStudent3()
Student Constructor2 Bill
Overload addStudent1()
*** List ***
1 Randy
3 Bill
3 Bill
*** EOF ***
Press any key to continue . . .

main.cpp
---------------------------------------------------------------------------------------

#include <cstdlib>
#include <iostream>
#include <vector>

// #include "Templates. h"
// #include "PointersAndRef erence.h"
#include "StudentsAndSch ools.h"
using namespace std;

int main(int argc, char *argv[])
{
// mypair<intok(10 ,23); // Declare an INT class w/
construction
// ok.printValues( );
// referenceTests( );

School sc;
sc.setNames("Pa rkside");

Student st = Student("Randy" );
Student * stp = & st;
sc.addStudent(s tp);

sc.addStudent(S tudent("Biff")) ;

Student st1 = Student("Bill") ;
Student * stp1 = & st1;
sc.addStudent(s tp1);
sc.getStudentNa mes();

system("PAUSE") ;
return EXIT_SUCCESS;
}

--------------- StudentsAndScho ols.h
-------------------------------------------------------------

#ifndef __StudentsAndSc hools__
#define __StudentsAndSc hools__

using namespace std;
class School;

class Student {

private:
static int mLastId;
string mName;
int mId;
School * mSchool;

public:
Student(){
cout << "Student Constructor1" << endl;
}
Student(string n){
cout << "Student Constructor2 " << n << endl;
mName = n;
mId = ++mLastId;
}
void setName(string n);
string getName();
int getId();
};
int Student::mLastI d = 0;

string Student::getNam e(){ return mName; };
int Student::getId( ){ return mId; };

class School{

private:
string mName;
vector<Student* mStudents;

public:
School(){
cout << "Schools Constructor 1" << endl;
}
void addStudent(Stud ent* );
void addStudent(Stud ent &); // overloaded
function
void addStudent(Stud ent);

void setNames(string n);
void getStudentNames ();
};

void School::setName s(string n){
mName = n;
}
void School::addStud ent(Student* n){
cout << "Overload addStudent1()" << endl;
mStudents.push_ back(n);
}
void School::addStud ent(Student &n ){
cout << "Overload addStudent2()" << endl;
Student * s = & n;
mStudents.push_ back(s);
}
void School::addStud ent(Student n ){
cout << "Overload addStudent3()" << endl;
Student * s = & n;
mStudents.push_ back(s);
}

void School::getStud entNames(){
cout << "*** List ***" << endl;
for(int i=0;i < mStudents.size( ); i++)
{
cout << mStudents.at(i)->getId() << " " <<
mStudents.at(i)->getName()<<end l;
}
cout << "*** EOF ***" << endl;
}
#endif

Apr 14 '07 #1
21 1431
Randy wrote:
Hi,

I am a noob. I am trying to store Student objects pointers, in a
vector, within a School object.
I call a setter function to add the pointer. If I use this method it
works,
Student st = Student("Randy" );
Student * stp = & st;
sc.addStudent(s tp);

My problem is passing a Student to the School function. I have an
overridden function. I try to create a pointer from the passed
Student. I bet that's my problem because it's a copy ?
Why not keep it simple and just use one addStudent member?
>
main.cpp
---------------------------------------------------------------------------------------

#include <cstdlib>
#include <iostream>
#include <vector>

// #include "Templates. h"
// #include "PointersAndRef erence.h"
#include "StudentsAndSch ools.h"
using namespace std;
You don't use anything from std::
int main(int argc, char *argv[])
{
// mypair<intok(10 ,23); // Declare an INT class w/
construction
// ok.printValues( );
// referenceTests( );

School sc;
sc.setNames("Pa rkside");

Student st = Student("Randy" );
Student * stp = & st;
sc.addStudent(s tp);

sc.addStudent(S tudent("Biff")) ;

Student st1 = Student("Bill") ;
Student * stp1 = & st1;
sc.addStudent(s tp1);
sc.getStudentNa mes();

system("PAUSE") ;
return EXIT_SUCCESS;
}

--------------- StudentsAndScho ols.h
-------------------------------------------------------------

#ifndef __StudentsAndSc hools__
#define __StudentsAndSc hools__
Don't use guards with leading double underscores, they are reserved.
>
using namespace std;
Never ever put a using directive in a header! It will apply in any file
that includes the header.
>
class School;

class Student {

private:
static int mLastId;
string mName;
int mId;
School * mSchool;

public:
Student(){
cout << "Student Constructor1" << endl;
}
Student(string n){
cout << "Student Constructor2 " << n << endl;
mName = n;
mId = ++mLastId;
}
void setName(string n);
string getName();
int getId();
};
int Student::mLastI d = 0;

string Student::getNam e(){ return mName; };
int Student::getId( ){ return mId; };
These will have to be declared "inline", or placed in a source file.
class School{

private:
string mName;
vector<Student* mStudents;

public:
School(){
cout << "Schools Constructor 1" << endl;
}
void addStudent(Stud ent* );
void addStudent(Stud ent &); // overloaded
function
Silly comment!
void addStudent(Stud ent);
You don't want this one, it is ambiguous.
--
Ian Collins.
Apr 14 '07 #2
On Apr 13, 8:37 pm, "Randy" <gast...@sympat ico.cawrote:
Hi,

I am a noob. I am trying to store Student objects pointers, in a
vector, within a School object.
In my opinion, you should be storing Students, not pointers to
Students.
I call a setter function to add the pointer. If I use this method it
works,
Student st = Student("Randy" );
Student * stp = & st;
sc.addStudent(s tp);

My problem is passing a Student to the School function. I have an
overridden function. I try to create a pointer from the passed
Student. I bet that's my problem because it's a copy ?
Its a copy alright, a copy of a pointer actually, unfortuanately -
copying pointers does not copy its pointee. And having a pointer to an
object does not guarentee that the object continues to exist.

This may sound a little strange to you right now but its fundamental
in C++. A dumb pointer is just a dumb pointer.
>
This all came about because I want to have a more succinct method for
doing this, just like the big kids do:
Student st = Student("Randy" );
Student * stp = & st;
sc.addStudent(s tp);

I've read lots but am apperantly missing the point. I am referencing
the C++ Primer.

here's my output too ... 2 Bills ?? ahaha ...

Schools Constructor 1
Student Constructor2 Randy
Overload addStudent1()
Student Constructor2 Biff
Overload addStudent3()
Stop right here. This should be your first clue. Take a look at that
member function:

void School::addStud ent(Student n ){
cout << "Overload addStudent3()" << endl;
Student * s = & n;
mStudents.push_ back(s);
}

You are storing pointers and yet parameter (Student n) ceases to exist
once the above member function terminates. Dumb pointer points to a
Student that is no longer.

The term is: dangling pointer
The result is: undefined behaviour
Student Constructor2 Bill
Overload addStudent1()
*** List ***
1 Randy
3 Bill
3 Bill
*** EOF ***
Press any key to continue . . .

main.cpp
---------------------------------------------------------------------------------------

#include <cstdlib>
#include <iostream>
#include <vector>

// #include "Templates. h"
// #include "PointersAndRef erence.h"
#include "StudentsAndSch ools.h"

using namespace std;

int main(int argc, char *argv[])
{
// mypair<intok(10 ,23); // Declare an INT class w/
construction
// ok.printValues( );
// referenceTests( );

School sc;
sc.setNames("Pa rkside");

Student st = Student("Randy" );
Student * stp = & st;
sc.addStudent(s tp);

sc.addStudent(S tudent("Biff")) ;

Student st1 = Student("Bill") ;
Student * stp1 = & st1;
sc.addStudent(s tp1);

sc.getStudentNa mes();

system("PAUSE") ;
return EXIT_SUCCESS;

}

--------------- StudentsAndScho ols.h
-------------------------------------------------------------

#ifndef __StudentsAndSc hools__
#define __StudentsAndSc hools__
Underscore + Capitale letter is reserved
2 Underscores + whatever is also reserved

#ifndef StudentsAndScho ols_h
#define StudentsAndScho ols_h

Although Student should have its own header and School ditto
>
using namespace std;
Using directives in a header file is a very bad idea.
>
class School;

class Student {

private:
static int mLastId;
string mName;
int mId;
School * mSchool;

public:
Student(){
cout << "Student Constructor1" << endl;
}
Student(string n){
cout << "Student Constructor2 " << n << endl;
mName = n;
mId = ++mLastId;
}
Initialize non-static members using an init list.

Student(std::st ring n) : mName(n), mId(++mLastId)
{
cout << "Student(std::s tring n) " << n << endl;
}

void setName(string n);
void setName(const std::string&);
string getName();
std::string getName() const;
int getId();};
int getId() const;
>
int Student::mLastI d = 0;

string Student::getNam e(){ return mName; };
int Student::getId( ){ return mId; };

class School{

private:
string mName;
vector<Student* mStudents;

public:
School(){
cout << "Schools Constructor 1" << endl;
}
void addStudent(Stud ent* );
void addStudent(Stud ent &); // overloaded
function
// the key is the constant keyword, the only version you need is by
const reference

void add(const Student&);

// the next "overload" prevents the former from being called although
the compiler should be generating a diagnostic about a conflict (which
one of these "overloads" should it call?).
void addStudent(Stud ent);

void setNames(string n);
void getStudentNames ();
const qualifiers missing above

<snip>
Apr 14 '07 #3
On Apr 13, 11:59 pm, "Salt_Peter " <pj_h...@yahoo. comwrote:
On Apr 13, 8:37 pm, "Randy" <gast...@sympat ico.cawrote:
Hi,
I am a noob. I am trying to store Student objects pointers, in a
vector, within a School object.

In my opinion, you should be storing Students, not pointers to
Students.
Here is an example without pointers. Note the Student's copy ctor and
the effects of uncommenting the std::vector's reserve in the School's
ctor.

#include <iostream>
#include <ostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>

class Student
{
int id;
std::string name;
public:
// ctors
Student() : id(0), name()
{
std::cout << "Student()\ n";
}
Student(int i, std::string n) : id(i), name(n)
{
std::cout << "Student(in t i, std::string n)\n";
}
// copy ctor
Student(const Student& copy)
{
std::cout << "Student(co nst Student& copy)\n";
id = copy.id;
name = copy.name;
}
// friend op
friend std::ostream& operator<<(std: :ostream&, const Student&);
};

std::ostream& operator<<(std: :ostream& os, const Student& r)
{
os << "id: " << r.id;
os << "\tname: " << r.name;
return os << std::endl;
}

class School
{
static int lastid;
std::string name;
std::vector< Student students;
public:
// ctor
School(std::str ing n) : name(n), students()
{
std::cout << "School()\n ";
// students.reserv e(64);
}
// member functions
void add(const std::string& s)
{
students.push_b ack( Student(++lasti d, s) );
}
// friend op
friend std::ostream& operator<<(std: :ostream&, const School&);
};

int School::lastid;

std::ostream& operator<<(std: :ostream& os, const School& r)
{
os << std::string(30, '-');
os << "\nschool: " << r.name;
os << "\nstudents : " << r.lastid;
os << std::endl;
std::copy( r.students.begi n(),
r.students.end( ),
std::ostream_it erator< Student >(os) );
os << std::string(30, '-');
return os << std::endl;
}

int main ()
{
School school("The Academy");
school.add("Alf red A");
school.add("Bet ty B");
school.add("Car l C");

std::cout << school;
}

/*
School()
Student(int i, std::string n)
Student(const Student& copy)
Student(int i, std::string n)
Student(const Student& copy)
Student(const Student& copy)
Student(int i, std::string n)
Student(const Student& copy)
Student(const Student& copy)
Student(const Student& copy)
------------------------------
school: The Academy
students: 3
id: 1 name: Alfred A
id: 2 name: Betty B
id: 3 name: Carl C
------------------------------
*/
Apr 14 '07 #4
On 13 Apr 2007 20:59:52 -0700, "Salt_Peter " wrote:
>On Apr 13, 8:37 pm, "Randy" <gast...@sympat ico.cawrote:
>I am trying to store Student objects pointers, in a
vector, within a School object.

In my opinion, you should be storing Students, not pointers to
Students.
Students are a classic objects (in the sense of OOP) which are
characterized by identity, state and behavior. You usually do not
duplicate (copy) and assign objects and therefore make their copy
constructor and assignment operator private. std::vector<Stu dentis
not a viable solution.
--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch
Apr 14 '07 #5
On Apr 14, 4:57 am, rpbg...@yahoo.c om (Roland Pibinger) wrote:
On 13 Apr 2007 20:59:52 -0700, "Salt_Peter " wrote:
On Apr 13, 8:37 pm, "Randy" <gast...@sympat ico.cawrote:
I am trying to store Student objects pointers, in a
vector, within a School object.
In my opinion, you should be storing Students, not pointers to
Students.

Students are a classic objects (in the sense of OOP) which are
characterized by identity, state and behavior. You usually do not
duplicate (copy) and assign objects and therefore make their copy
constructor and assignment operator private. std::vector<Stu dentis
not a viable solution.

--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch

Thank you very much for sharing your time and experience. You more
than answered my questions and now I have some focused learning to do.
Randy

Apr 14 '07 #6
I V
On Sat, 14 Apr 2007 08:57:23 +0000, Roland Pibinger wrote:
Students are a classic objects (in the sense of OOP) which are
characterized by identity, state and behavior. You usually do not
Really? I would have thought that Randy's Student class is a classic
_value_. Their identity is defined by equivalence (I don't
think you would want to treat students with the same name, at the same
school, with the same id, as being different), and they don't really have
any behavior (the only methods the class has are accessors). Why do you
think they should be considered entities?
Apr 14 '07 #7
On Apr 14, 4:57 am, rpbg...@yahoo.c om (Roland Pibinger) wrote:
On 13 Apr 2007 20:59:52 -0700, "Salt_Peter " wrote:
On Apr 13, 8:37 pm, "Randy" <gast...@sympat ico.cawrote:
I am trying to store Student objects pointers, in a
vector, within a School object.
In my opinion, you should be storing Students, not pointers to
Students.

Students are a classic objects (in the sense of OOP) which are
characterized by identity, state and behavior. You usually do not
duplicate (copy) and assign objects and therefore make their copy
constructor and assignment operator private. std::vector<Stu dentis
not a viable solution.

--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch

On what basis is the solution not viable?
Are you suggesting that a Student Record is not usueable elsewhere?
Why should a program or program(s) not have a dataset that is copyable
in order to process it in whatever way it does? What makes you beleive
that a copy implies a duplicate? (its not in the proposed std::vector<
Student solution)
For all we know, that dataset is read and stored to file.

Why further complicate a program by a std::vector< Student* where
the Student's allocation is then given to yet another entity?
(Specially since we are dealing here with an OP that is having issues
with dangling pointers)

Apr 14 '07 #8
On Apr 14, 10:57 am, rpbg...@yahoo.c om (Roland Pibinger) wrote:
On 13 Apr 2007 20:59:52 -0700, "Salt_Peter " wrote:
On Apr 13, 8:37 pm, "Randy" <gast...@sympat ico.cawrote:
I am trying to store Student objects pointers, in a
vector, within a School object.
In my opinion, you should be storing Students, not pointers to
Students.
Students are a classic objects (in the sense of OOP) which are
characterized by identity, state and behavior.
I don't think he's given us enough information to draw that
conclusion. It depends on the role and the responsibilitie s of
the class in the actual application. If all the class
represents is a specific identity, it could be given value
semantics. If it has some real behavior, then it's probably an
entity object, and identity becomes important. (And of course,
if identity is important, you block copy and assignment, as you
said.)

--
James Kanze (Gabi Software) email: ja*********@gma il.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 15 '07 #9
On Sat, 14 Apr 2007 19:24:43 +0000 (UTC), I V <iv*****@gmail. com>
wrote:
>On Sat, 14 Apr 2007 08:57:23 +0000, Roland Pibinger wrote:
>Students are a classic objects (in the sense of OOP) which are
characterize d by identity, state and behavior. You usually do not

Really? I would have thought that Randy's Student class is a classic
_value_. Their identity is defined by equivalence (I don't
think you would want to treat students with the same name, at the same
school, with the same id, as being different), and they don't really have
any behavior (the only methods the class has are accessors). Why do you
think they should be considered entities?
What should the following mean?

Student Ivlenin;
Student Randy = Ivlenin;
--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch
Apr 15 '07 #10

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

Similar topics

27
3389
by: Susan Baker | last post by:
Hi, I'm just reading about smart pointers.. I have some existing C code that I would like to provide wrapper classes for. Specifically, I would like to provide wrappers for two stucts defined as ff: typedef struct { float *data ; int count ;
3
3441
by: ozbear | last post by:
This is probably an obvious question. I know that pointer comparisons are only defined if the two pointers point somewhere "into" the storage allocated to the same object, or if they are NULL, or one-past the end of the object as long as it isn't dereferenced. I use "object" in the standard 'C' sense. Is there some special dispensation given to comparing two pointers
9
5054
by: Mikhail Teterin | last post by:
Hello! I'd like to have a variable of a pointer-to-function type. The two possible values are of type (*)(FILE *) and (*)(void *). For example: getter = straight ? fgetc : gzgetc; nextchar = getter(file); What type should I give to `getter' so that the compiler does not issue
12
4075
by: Lance | last post by:
VB.NET (v2003) does not support pointers, right? Assuming that this is true, are there any plans to support pointers in the future? Forgive my ignorance, but if C# supports pointers and C# and VB.NET get compiled into the same code, then I don't understand why VB.NET can't support pointers Thanks for any info Lance
14
2819
by: Alf P. Steinbach | last post by:
Not yet perfect, but: http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01.pdf http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01_examples.zip To access the table of contents, use the "Bookmarks" tab in Adobe Acrobat. Comments, corrections, praise, nits, etc., are still welcome!
92
5051
by: Jim Langston | last post by:
Someone made the statement in a newsgroup that most C++ programmers use smart pointers. His actual phrase was "most of us" but I really don't think that most C++ programmers use smart pointers, but I just don't know. I don't like them because I don't trust them. I use new and delete on pure pointers instead. Do you use smart pointers?
4
3501
by: Josefo | last post by:
Hello, is someone so kind to tell me why I am getting the following errors ? vector_static_function.c:20: error: expected constructor, destructor, or type conversion before '.' token vector_static_function.c:21: error: expected constructor, destructor, or type conversion before '.' token
25
13017
by: J Caesar | last post by:
In C you can compare two pointers, p<q, as long as they come from the same array or the same malloc()ated block. Otherwise you can't. What I'd like to do is write a function int comparable(void *p, void *q) that will take any two pointers and decide whether they can be compared or not. I really can't think how to do this - any suggestions?
54
11957
by: Boris | last post by:
I had a 3 hours meeting today with some fellow programmers that are partly not convinced about using smart pointers in C++. Their main concern is a possible performance impact. I've been explaining the advantages of smart pointers endlessly (which are currently used in all our C++ software; we use the Boost smart pointers) as I'm seriously concerned that there is a shift to raw pointers. We are not developing system software but rather...
0
8251
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8182
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
8688
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
8352
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
8494
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...
0
7178
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4085
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
4188
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2614
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.