D
DamonChong
Hi, I am new and had this piece of code which I created but it is not
behaving as expected. I'm using g++, can someone help me out? Thank
you.
//--------file (Object.cc)-----------
class Object {
public:
Object(const char * c){
id = c;
}
~Object() {}
const char * get_id() const { return id; }
private:
const char * id;
};
//-------file (Test.cc)-------------
#include <iostream>
#include <sstream>
#include "Object.cc"
class Test{
public:
Object ** obj;
Test(){
obj = new Object * [3];
for( int i=0; i<3; i++ ){
std:stringstream os;
os << i;
obj = new Object( os.str().c_str() );
std::cout << "Created id = " << obj->get_id() <<
std::endl;
}
}
~Test(){}
};
int main() {
Test t;
for(int i=0; i<3; i++){
std::cout << "Object id - " << t.obj->get_id()
<< " // expecting " << i << std::endl;
}
}
//----------------output upon running------------
=> ./Test
Created id = 0
Created id = 1
Created id = 2
Object id - 2 // expecting 0
Object id - 2 // expecting 1
Object id - 2 // expecting 2
My query is if I changed the "const char *" to simply int as the
parameter to pass the Object constructor like this and make the
appropriate changes, it works as expected. Now, I know i'm missing
something here!
//---------------file (Object1.cc)-----------------
class Object1 {
public:
Object1(int c){
id = c;
}
~Object1() {}
const int get_id() const { return id; }
private:
int id;
};
behaving as expected. I'm using g++, can someone help me out? Thank
you.
//--------file (Object.cc)-----------
class Object {
public:
Object(const char * c){
id = c;
}
~Object() {}
const char * get_id() const { return id; }
private:
const char * id;
};
//-------file (Test.cc)-------------
#include <iostream>
#include <sstream>
#include "Object.cc"
class Test{
public:
Object ** obj;
Test(){
obj = new Object * [3];
for( int i=0; i<3; i++ ){
std:stringstream os;
os << i;
obj = new Object( os.str().c_str() );
std::cout << "Created id = " << obj->get_id() <<
std::endl;
}
}
~Test(){}
};
int main() {
Test t;
for(int i=0; i<3; i++){
std::cout << "Object id - " << t.obj->get_id()
<< " // expecting " << i << std::endl;
}
}
//----------------output upon running------------
=> ./Test
Created id = 0
Created id = 1
Created id = 2
Object id - 2 // expecting 0
Object id - 2 // expecting 1
Object id - 2 // expecting 2
My query is if I changed the "const char *" to simply int as the
parameter to pass the Object constructor like this and make the
appropriate changes, it works as expected. Now, I know i'm missing
something here!
//---------------file (Object1.cc)-----------------
class Object1 {
public:
Object1(int c){
id = c;
}
~Object1() {}
const int get_id() const { return id; }
private:
int id;
};