c++ forward declaration + ifndef also needs pointers [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Array:
#ifndef ARRAY_H
#define ARRAY_H
#include <bits/stdc++.h>
using namespace std;
namespace Maifee{
class Value;
class Array {
public:
Array();
vector<Value> _elements;
};
}
#endif // ARRAY_H
Object :
#ifndef OBJECT_H
#define OBJECT_H
#include <bits/stdc++.h>
#include "value.h"
using namespace std;
namespace Maifee{
class Value;
class Object{
public:
Object();
map<string, Value> _members;
};
}
#endif // OBJECT_H
Value :
#ifndef VALUE_H
#define VALUE_H
#include <bits/stdc++.h>
#include "array.h"
#include "object.h"
using namespace std;
namespace Maifee{
class Array;
class Object;
class Value {
public:
Value();
Value(Object *__object);
Array *_array;
Object *_object;
};
}
#endif // VALUE_H
I'm learning C++ at my best. With my teeny tiny knowledge in C++, I am trying to write some code. First reason I'm moving C++, pointers take a lot's of time.
Here I'm writing these code, where forward-declaration is necessary, and due to this even after using forward-declaration and ifndef, I need to use pointer, which I really don't want.
Can anyone really help me with this, how can I remove circular dependency??
Do I need to go back to C?
When using pointer I faced many problems such as, I have just one key-value pair in my map, but in the next line size becomes a very large number, out of nowhere.
Code inside main :
Object object=Object();
cout << "pop obj tem len" << object._members.size() << endl; //gives 0 as expected
object._members = members;
cout << "pop obj tem len" << object._members.size() << endl; //gives the expected number
Value val=Value(&object);
cout << val._object->_members.size() << "size here" << endl; //gives a random number
Constructor for Value with Object parameter :
Value::Value(Object *__object)
{
Object object;
object._members.insert(__object->_members.begin(), __object->_members.end());
_object = &object;
}

You can't avoid the forward-declarations and pointers in this situation.
class Object has a map<string, Value> member, and class Array has a vector<Value> member. Which means Value must be a fully-defined, complete type by the time Object and Array are being compiled, as map and vector need to know the total size of their element types. If Value were to have non-pointer Array and Object members, then Object and Array would need Value to be a complete type, but Value would need Object and Array to be complete types. Catch-22!
So, you have to use forward declarations and pointers/references for the Value members in order to make this kind of circular referencing work properly, since pointers/references to incomplete types are allowed.
UPDATE: In your Value constructor that takes an Object* parameter, you are setting the _object member to point at a local Object instance that goes out of scope and is destroyed when the constructor exits, thus leaving _object dangling. That is why the subsequent val._object->_members.size() expression in main() produces garbage (you are lucky the code didn't crash outright) - val._object is pointing at invalid memory, so its members is not a valid map object and so reading its size() is undefined behavior. That goes right back to the original comment I posted:
You are likely accessing an invalid pointer.
To solve this, depending on your actual design goal, the Value constructor needs to either:
construct a new Object dynamically, which will have to be delete'd later. You will also have to provide a proper copy constructor and copy assignment operator:
Value::Value()
{
_object = NULL;
_array = NULL;
}
Value::Value(Object *__object)
{
_object = new Object;
_array = NULL;
if (__object)
_object._members = __object->_members;
}
Value::Value(const Value &__value)
{
_object = new Object;
_array = NULL;
if (__value._object)
_object._members = __value._object->_members;
}
Value::~Value()
{
delete _object;
}
Value& Value::operator=(const Value &__value)
{
if (&__value != this)
{
Value tmp(__value);
std::swap(_object, tmp._object);
std::swap(_array, tmp._array);
}
return *this;
}
simply store the Object* pointer it is given:
Value::Value(Object *__object)
{
_object = __object;
_array = NULL;
}

Related

Why does my class std::vector member always throw a segfault?

I've searched endlessly on SE for a logical explanation for why this is happening. It is probably something very simple that I've overlooked, however I cannot spot it and would really appreciate some assistance with this.
Last week I implemented a class to read the output of a system call from a .ini file and then find and store the required information into custom objects that are then stored in a vector inside a Config class. It is a Singleton config class storing a unique_ptr for each instance of my custom class that is created.
The thing is, when I implemented this last week on my laptop, I had zero issues reading and writing to my member vector and was able to get it working exactly how I needed it. Since pulling to my desktop computer, this vector, and any STL container that I use as a member of my class, throws a segmentation fault when I try to do anything on it, even get it's size.
I've tried to shorten the code below to only include sections that actually use this vector. I have replaced my config with A, and custom class with T, and no matter where I try to use my member container, or any other test STL containers that I add to the class, I get a segfault.
For the record, I am using Qt with C++11.
Update: This example breaks on line 50 of c.cpp when debugging, and anywhere that tries to call the vector.
Debug points to this line in stl_vector.h
// [23.2.4.2] capacity
/** Returns the number of elements in the %vector. */
size_type
size() const _GLIBCXX_NOEXCEPT
/*-> this line */ { return size_type(this->_M_impl._M_finish - this->_M_impl._M_start); }
main.cpp
#include "c.h"
int main(int argc, char *argv[])
{
C *c = C::getInstance();
delete c;
return 0;
}
t.h - Class stores information from file
#include <string>
class T
{
public:
T();
bool Active();
std::string getA();
void setA(std::string);
private:
std::string a;
};
t.cpp
#include "t.h"
T::T()
{
}
bool T::Active()
{
if(a == "")
{
return false;
}
return true;
}
std::string T::getA()
{
return this->a;
}
void T::setA(std::string newa)
{
this->a = newa;
}
c.h - Class stores T objects and parses file for information
#include "t.h"
#include <QDebug>
#include <vector>
#include <algorithm>
#include <iostream>
#include <memory>
#include <sstream>
#include <fstream>
class C
{
public:
static C* getInstance();
private:
C();
static C* instance;
static bool init;
std::vector<std::unique_ptr<T>> t_list;
void readLines(const std::string&);
};
c.cpp
#include "c.h"
bool C::init = false;
C* C::instance = nullptr;
C::C()
{
system("echo this is a test command > a.ini");
instance->readLines("a.ini");
}
C* C::getInstance()
{
if(!init)
{
instance = new C;
init = true;
}
return instance;
}
void C::readLines(const std::string &path)
{
T* new_t;
std::ifstream file(path.c_str());
if(!file.is_open())
{
qDebug() << "Unable to open " << path.c_str();
}
std::ofstream o("test.txt");
std::string line;
while(std::getline(file, line))
{
// Split string before searching
std::stringstream ss(line);
std::string seg;
std::vector<std::string> split;
std::string left, right;
// Search patterns
size_t find_a = line.find("a");
size_t del = line.find(':');
if(find_a != std::string::npos)
{
o << "test_Size: " << t_list.size() << std::endl;
if(new_t->Active())
{
T* temp = new_t;
std::unique_ptr<T> move_t(temp);
t_list.push_back(std::move(move_t));
}
o << "test: " << t_list.size() << std::endl;
std::string n;
// Check if previous ahas any null elements
// Split string to find a
n = line.substr(line.find("a "));
n = n.substr(n.find(" ", +2));
new_t->setA(n);
}
else
{
continue;
}
}
// Add last a
T* t = new_t;
std::unique_ptr<T> move_t(t);
//t_list.push_back(std::move(move_t));
o << "a: " << t_list.back().get()->getA() << std::endl;
o << t_list.size() << std::endl;
o.close();
file.close();
}
UPDATE after code change:
I see two things now: One is that new_t in C::readlines is never initialized, so this could break when new_t->Active() is called a bit later in the function. However, I believe that the main problem you're running into is in C::C(), where it says
instance->readLines("a.ini");
At this point in the execution, C::instance is not yet initialized -- you're only just constructing the object that would later be assigned to it. Because of this, this in the readlines call is invalid, and any attempt to access object members will cause UB. This latter problem can be fixed by just calling
readLines("a.ini");
in which case the currently constructed object (that will later be instance) is used for this. I have no idea what you want to happen for the first, though, so all I can say is: If you want to have a vector<unique_ptr<T>>, you will have to create objects of type T with either new T() or (arguably preferrably) std::make_unique<T>() and put them in there.
I'll also say that this is a rather ugly way to implement a singleton in C++. I mean, singletons are never really pretty, but if you're going to do it in C++, the usual way is something like the accepted answer of C++ Singleton design pattern .
Old answer:
The problem (if it is the only one, which I cannot verify because you didn't provide an MCVE) is in the lines
T move_t = new_T;
std::unique_ptr<Adapter> ptr_t(&move_t); // <-- particularly this one
m_ts.push_back(std::move(ptr_t));
You're passing a pointer to a local object into a std::unique_ptr, but the whole purpose of std::unique_ptr is to handle objects allocated with new to avoid memory leaks. Not only will the pointer you pass into it be invalid once the scope surrounding this declaration is left, even if that weren't the case the unique_ptr would attempt to delete an object that's not on the heap at the end of its lifecycle. Both problems cause undefined behavior.
To me, it looks as though you really want to use a std::vector<T> instead of std::vector<std::unique_ptr<T>>, but that's a design issue you'll have to answer yourself.
Answering my own question here. I am trying to call a member variable from within the constructor of the object that holds it, so the vector I am trying to access is not yet instantiated and doesn't exist in memory. That is what causes the Segmentation fault to occur, I am trying to access memory that is not allocated yet, hence any call acting on any member of my C class was causing this issue.
I fixed this problem by adding a public function to the class that then calls the private readLines() function. I call that public function from the object that will take ownership of it, and since this occurs after it has been instantiated, the memory is accessible and the problem disappears.

C++ Dynamic Array Member Variable Assignment

I am having a problem with assigning new values to a dynamic int array that is a data member variable of the class IntersectionFlowRate(). I can initialize and print the values of the array inside the constructor. However, when I exit the constructor to the another class and then later call a function within the IntersectionFlowRate() class passing in variables to overwrite the initial values of the data member it will segmentation fault. I have debugged to find that overwriting the array is causing the seg fault. And that even attempting to access the dynamic array within one of its functions will seg fault.
My question is how can I edit the values of a dynamic int array member variable from within one of its functions i.e setArrayElement(int index, int x).
Here is some of my code. Sorry if I am unclear or missing something ridiculous. I have been stuck on this for hours.
#ifndef INTERSECTIONFLOWRATE_H
#define INTERSECTIONFLOWRATE_H
class IntersectionFlowRate
{
public:
IntersectionFlowRate();
~IntersectionFlowRate();
void setFlowCycle(int index, int flow);
private:
int* m_flowRateMotorCycle;
};
#endif
in the .h file ^
#include "IntersectionFlowRate.h"
#include <cstdlib>
#include <iostream>
#include <new>
using namespace std;
IntersectionFlowRate::IntersectionFlowRate()
{
const int SIZE = 4; //Constant for m_flowRates[] size
//DYNAMIC MEMORY DELETE LATER
m_flowRateMotorCycle = new int[SIZE];
for(int i = 0; i < SIZE; i++){
m_flowRateMotorCycle[i] = 0;
cout << m_flowRateMotorCycle[i] << endl;
cout << "WE GOT HERE" << endl;
}
}
void IntersectionFlowRate::setFlowCycle(int index, int flow){
cout << "INDEX: " << index << endl;
cout << "FLOW: " << flow << endl;
m_flowRateMotorCycle[index] = flow; //seg fault is here
}
I have another class that creates a pointer to a IntersectionFlowRate() object and then calls its setFlowCycle function passing in two VALID ints. With the debugging I was able pass 0 and 3 to the function setFlowCycle(0, 3) just fine and output those variables within the function.
#ifndef TRAFFICSIM_H
#define TRAFFICSIM_H
#include "IntersectionFlowRate.h"
using namespace std;
class TrafficSim
{
public:
TrafficSim(); //Default Constructor
TrafficSim(const char* file); //Constructor
~TrafficSim(); //Destructor
private:
IntersectionFlowRate* m_flowRate;
};
#endif
#include "TrafficSim.h"
#include "IntersectionFlowRate.h"
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
TrafficSim::TrafficSim()
{
IntersectionFlowRate* m_flowRate = new IntersectionFlowRate();
m_flowRate->setFlowCycle(0, 3);
}
I replicated the error with this code. If no one else can I am completely unsure of what is possibly wrong anymore.
You are setting a local variable called m_flowRate, not the member variable m_flowRate of your TrafficSim class:
Instead of this:
TrafficSim::TrafficSim()
{
IntersectionFlowRate* m_flowRate = new IntersectionFlowRate();
m_flowRate->setFlowCycle(0, 3);
}
It should be this:
TrafficSim::TrafficSim()
{
m_flowRate = new IntersectionFlowRate();
m_flowRate->setFlowCycle(0, 3);
}
But overall, it not need be a pointer. It could be an object member within your class. That would cut down on the pointer usage a bit:
class TrafficSim
{
public:
TrafficSim(); //Default Constructor
TrafficSim(const char* file); //Constructor
private:
IntersectionFlowRate m_flowRate;
};
Then:
TrafficSim::TrafficSim()
{
m_flowRate.setFlowCycle(0, 3);
}
As to your question as to how to incorporate usage of std::vector in your class, here is a code sample of the IntersectionFlowRate class, rewritten using vector:
Vector sample
Also, another source of problems is that your classes fail to follow the Rule of 3 when you have pointers to dynamically allocated memory in your class.
Using std::vector takes care of this automatically, but if you insist on using pointers, you need to adhere to the directions at the link posted.
Yes, use a std::vector, it is much simpler, and it is a template so it also pretty fast and works any type (best for primitive types or pointers to objects) , and it also has boundary checking and other useful things.
If you need fast array-like access then you could use std::map which associates a key with a value, like so
std::map<UINT, YourClass*> m_mapIDs_to_YourClass;
When you first start using stl containers they might seem a little strange, but after a short while you cannot do without them, luckily they have been part of the C++ standard for some time now.
Boundary check for both these containers can be done by comparing your iterator to mapYourMap.end(), if they are equal you have passed the last element and trying to access data through the iterator will cause an exception.
Example for std::vector (if vecInt is a vector< int >):
vector<int>::iterator it = vecInt.begind();
if (it == vecInt.end()) return; // vector is empty
do { // runs through elememts until out of bound, useful for searching
i++
while (it != vecInt.end());

Filing a vector outside of a function in a class

Fairly simple question here, whats the best way to fill a vector outside of a function in a class .cpp file? currently i'm attempting the following which is not working:
std::vector<Player> midfielder(8);
midfielder.at(0) = Midfielder("Default ",0,"Midfielder");
midfielder.at(1) = Midfielder("David Armitage ",1,"Midfielder");
midfielder.at(2) = Midfielder("Tom Rockliff ",2,"Midfielder");
midfielder.at(3) = Midfielder("Gary Ablett ",3,"Midfielder");
midfielder.at(4) = Midfielder("Dyson Heppel ",4,"Midfielder");
midfielder.at(5) = Midfielder("Scott Pendlebury",5,"Midfielder");
midfielder.at(6) = Midfielder("Michael Barlow ",6,"Midfielder");
midfielder.at(7) = Midfielder("Jack Steven ",7,"Midfielder");
To provide context, 'Midfielder' is a class that inherits from the 'Player' class.
TeamManagment.h
#ifndef TEAMMANAGEMENT_H
#define TEAMMANAGEMENT_H
#include <vector>
#include "Player.h"
#include "Midfielder.h"
#include <string>
class TeamManagement
{
public:
TeamManagement();
void Display_Players();
};
#endif // TEAMMANAGEMENT_H
TeamManagement.cpp
#include <iostream>
#include <string>
#include <vector>
#include "Player.h"
#include "Midfielder.h"
#include "TeamManagement.h"
using namespace std;
TeamManagement::TeamManagement()
{
}
std::vector<Player> midfielder(8);
//errors start occurring on line below: 'midfielder' does not name a type
midfielder.at(0) = Midfielder("Default ",0,"Midfielder");
midfielder.at(1) = Midfielder("David Armitage ",1,"Midfielder");
midfielder.at(2) = Midfielder("Tom Rockliff ",2,"Midfielder");
midfielder.at(3) = Midfielder("Gary Ablett ",3,"Midfielder");
midfielder.at(4) = Midfielder("Dyson Heppel ",4,"Midfielder");
midfielder.at(5) = Midfielder("Scott Pendlebury",5,"Midfielder");
midfielder.at(6) = Midfielder("Michael Barlow ",6,"Midfielder");
midfielder.at(7) = Midfielder("Jack Steven ",7,"Midfielder");
//errors stop occurring here
void TeamManagement::Display_Players(){
cout<<"Position Name ID"<<endl;
for (int i=1;i<8;i++)
{
cout<<midfielder[i].Player_Details()<<" "<<midfielder[i].Get_player_id()<<endl;
}
}
The first problem is that you cannot perform assignment like that outside of a function. You must use construction or initialization.
With C++98 you cannot populate/initialize a vector outside of a function.
With C++11/14 you can populate one using initializer syntax:
#include <iostream>
#include <vector>
struct Thing {
int m_i, m_j;
Thing(int i, int j) : m_i(i), m_j(j) {}
};
std::vector<Thing> things {
{ 1, 2 }, { 2, 3 }
};
int main() {
std::cout << "things[0].m_j = " << things[0].m_j << '\n';
}
But std::vector won't like you trying to put "Midfielder"s into a vector of Player. Lets use an SSCCE to reconstruct the damage you're doing:
#include <iostream>
struct Base {
int i;
};
struct Derived : public Base {
int j;
};
int main() {
std::cout << "Base size = " << sizeof(Base) << '\n';
std::cout << "Derived size = " << sizeof(Derived) << '\n';
}
This tells us that Base and Derived have a different size. But you're trying to put these two objects into the same container because they're related. Round peg and square peg are related... They won't fit into the same hole, and this is the problem we have now.
The vector creates space in memory for your elements based on the type you supply, and then it requires you to pass it exactly that type to populate those spaces with, or a type that has a conversion mechanism to the storage type.
If you want to have a container of different types, you'll need to use pointers, but then you're going to run into the problem that what you get back will be a pointer to the base type and you will need to provide yourself with a way to distinguish different player types.
See Store derived class objects in base class variables for the C++98 approach. In modern C++ (11 and 14) you should use smart pointers, e.g.
std::vector<std::unique_ptr<Base>>
std::vector<std::shared_ptr<Base>>
Presumably default constructing a Midfielder doesn't make a lot of sense, so you can reserve the memory, then emplace_back into the vector.
std::vector<Player> midfielder {};
midfielder.reserve(8);
midfielder.emplace_back("Default ",0,"Midfielder");
midfielder.emplace_back("David Armitage ",1,"Midfielder");
midfielder.emplace_back("Tom Rockliff ",2,"Midfielder");
midfielder.emplace_back("Gary Ablett ",3,"Midfielder");
midfielder.emplace_back("Dyson Heppel ",4,"Midfielder");
midfielder.emplace_back("Scott Pendlebury",5,"Midfielder");
midfielder.emplace_back("Michael Barlow ",6,"Midfielder");
midfielder.emplace_back("Jack Steven ",7,"Midfielder");
midfielder.at(0) = Midfielder("Default ",0,"Midfielder"); is a statement. You've put that and similar statements in (global) namespace scope. That's your bug. Only declarations may be in namespace scope. You must put your statements inside a function.
The error message stems from the fact that declarations which don't start with a keyword start with a type name. Since midfielder is not a keyword, the compiler expects it to be a type name but it isn't one, so you get the error.

Passing a reference to an object for mutation C++

I have an object with a method that needs to mutate an outside instantiated object. I've been trying to reference the object in the parameter and that is clearly not working. This is what I have:
#include <iostream>
#include <cstdlib>
#include "Character.h"
using namespace std;
class TesterClass {
public:
void printStuff();
TesterClass(Character& userChar);
private:
Character& character;
};
TesterClass::TesterClass(Character& userChar)
{
character = userChar;
}
int main() {
Character userCharacter;
TesterClass tester(userCharacter);
return 0;
}
My question is how to can I use the instantiated tester class to edit the Character object via parameter passing. I'm very new at C++ and I've read every perceivable definition of reference and point passing, and it just doesn't seem to want to click.
Your constructor should be:
TesterClass::TesterClass(Character& userChar):character(userChar){}
Also see this question.
To address the comment, here's example code where the value is modified:
#include <iostream>
#include <cstdlib>
typedef char Character;
using namespace std;
class TesterClass {
public:
void printStuff();
TesterClass(Character& userChar);
private:
Character& character;
};
TesterClass::TesterClass(Character& userChar):character(userChar)
{
}
void TesterClass::printStuff() {
cout << character << endl;
cout << ++character << endl;
}
int main() {
Character userCharacter = 'a';
TesterClass tester(userCharacter);
tester.printStuff();
cout << userCharacter << endl;
++userCharacter;
cout << userCharacter << endl;
tester.printStuff();
return 0;
}
The output is
a
b
b
c
c
d
I agree with the previous answer/comments - You really should use an initialization list in your constructor. The thing is that your data-members are initialized through the initialization list (this happens BEFORE the body of the constructor is called). In your case, you have a Character& as a member. Since this is a reference, it HAS to be assigned something. I'm not sure which compiler you're using, but AFAIK that code shouldn't even compile.
What you're probably looking for is passing the reference in your main-method, like:
int main()
{
Character userCharacter;
// Notice the use of the &-operator
TesterClass tester(&userCharacter);
return 0;
}
At this point, you're no longer talking about a Character-instance, but of the memory address of the instance. So, since you're passing the mem-address, it's actually a pointer you need in your class, not a reference. (For instance, userCharacter.SomeMethod() is synonymous to (&userCharacter)->SomeMethod() where & references and -> dereferences).
Instead, you could write your TesterClass as:
class TesterClass
{
public:
void printStuff();
TesterClass(Character* userChar);
private:
Character* character;
};
TesterClass::TesterClass(Character* userChar)
: character(userChar) // <- Notice the init-list
{}
That way, in your TesterClass instance, you'll have a pointer that points to the same memory address where the userChar-instance resides.
As a sidenote: It can be good to notice though that userCharacter is a local variable, which means that it'll be destroyed when it runs out of scope. In this case it's not really a problem since tester is local as well. But if you're not used to working with pointers - Just a word of caution. Make sure you never pass the pointer (since you're storing the address in a class member) to a TesterClass-object that lives beyond the scope of the variable whose reference you're passing. That'll leave you with a dangling pointer.
I hope that helps you :)

handing pointers in a class

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class newclass
{
public:
string *Date;
void show(){ cout << this->Date;}
};
int main()
{
newclass *n = new newclass;
n->Date = new string ;
n->Date.assign("hello"); // get an error on this line
n->show();
return 0;
}
Can Somebody please explain me how this works?. I am new to this.
n->Date->assign("hello") because n->Date is a pointer, so you must dereference it before calling a function on it.
Please look at this SO Question for a detailed explanation of the syntax.
It looks like you're applying idioms from another language. In C++ you should avoid pointers whenever possible, replaced by member or local variables. Your code in that case would look like this:
class newclass
{
public:
string Date;
void show(){ cout << this->Date;}
};
int main() {
newclass n;
n.Date.assign("hello");
n.show();
return 0;
}
You've got a few problems here, let's go over them one at a time:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class newclass
{
public:
// This is a pointer to a std::string, that doesn't appear to
// be allocated. From this small example, you don't really need
// a pointer at all:
// string *Date;
// now that this object isn't a pointer, you can use dot syntax
// to access its member functions
string Date;
void show()
{
// accessing date through this-> is not necessary
// here. You can simply use Date. However since this
// doesn't cause any specific problems I mention it only
// as informational
cout << this->Date;
}
};
int main()
{
newclass *n = new newclass;
// This is bad practice, you generally shouldn't be allocating
// objects within a class outside of that class's implementation.
// this would better be done in the newclass constructor.
// n->Date = new string ;
// Since we replaced the pointer to string object Date in newclass
// and replaced it with an automatic string object, this line will
// now work as written.
n->Date.assign("hello"); // get an error on this line
n->show();
// At this point your program will exit, and newclass is shown as
// a memory leak. While the OS will reclaim this memory at application
// exit, its good to get used to managing the lifetime of your objects
// appropriate. This has do be deleted, or better yet wrapped in a smart
// pointer
delete n;
return 0;
}
To provide an example that is similar to your original question, let's take the following code:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <memory>
using namespace std;
class newclass
{
public:
// auto_ptr is a smart pointer class that
// wraps a dynamically allocated object and
// provides cleanup for it when it goes out
// of scope. So when our class goes out of
// scope the Date object will be cleaned up
// for us
auto_ptr<string> Date;
// this is the constructor of the newclass object
// its called anytime a newclass object is instantiated
// we use the initializer list to allocate the Date object
newclass() : Date(new string)
{
}
// a mutator for setting the Date object (promotes encapsulation)
void set_date(const std::string& val)
{
// necessary to dereference to get at the date object
(*Date) = val;
}
void show() { cout << this->Date; }
};
int main()
{
// note the use of an auto_ptr here for automatic cleanup
auto_ptr<newclass> n(new newclass);
// use our mutator method to set the date
n->set_date("hello");
n->show();
return 0;
}
Date is itself a pointer to string, you will need to dereference it as well:
n->Date->assign("hello");
newclass *n = new newclass;
n->Date = new string ;
n->Date->assign("hello"); // use -> when accessing a member of a pointer
n->show();