none
none

Reputation:

how to change address of variable?

i have

Tree<std:string> tree;

now

new Tree<std:string>;

leads to a pointer, how can i change address of tree to that of pointer generated by new?

Upvotes: 0

Views: 6119

Answers (4)

mloskot
mloskot

Reputation: 38912

I'd also recommend to read Alok's comment and think a bit about it.

Here you have examples of alternative approaches of transition from automatic storage to dynamic storage. It uses std::vector as equivalent to your Tree class, but it can be any type you like.

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using namespace std;

int main()
{
   vector<string> v(3);
   v[0] = "abc";
   v[1] = "def";
   v[2] = "ghi";

   // option #1 - make a copy
   {
      vector<string>* pv = new vector<string>(v);
      std::copy(pv->begin(), pv->end(), std::ostream_iterator<string>(cout, ", "));
      delete pv;
   }
   cout << endl;

   // option #2 - move content from original vector to new'ed one
   {
      vector<string>* pv = new vector<string>();
      pv->swap(v);
      std::copy(pv->begin(), pv->end(), std::ostream_iterator<string>(cout, ", "));
      delete pv;
   }
}

Upvotes: 0

avakar
avakar

Reputation: 32635

Making C++ code look like Java is a bad idea, the two languages are very different.

That said, in C++ operator new returns a pointer to the allocated object.

Tree<std::string> * tree = new Tree<std::string>;
tree->do_something();

You can also bind a reference to your object.

Tree<std::string> & tree2 = *tree;
tree.do_something();

I urge you not to do that. Writing -> instead of . is not that difficult.

Upvotes: 6

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76541

You can't. Creating an object using Tree<std:string> tree; creates tree at some specific place in memory and you can't change that.

Perhaps what you want is to make tree be a pointer Tree<std:string> *tree = 0;. When you do that, tree is no longer an object but a pointer. You can then make it point to an object by assigning the return from new tree = new Tree<std::string>;

Upvotes: 2

SurDin
SurDin

Reputation: 3341

I think you're a little confused here. In C++ when you declare an object, the constructor is called automatically, you don't need to new it. After doing:

Tree<std:string> tree;

You can access tree already, and its constructor has been called.

It is already a constructed object. If you want to have a pointer, and construct an object in the heap, and no the stack, you need to do,

Tree<std:string> *tree;
tree  = new Tree<std:string>;

And then use *tree to access tree. You can see how it works if you add a printf statement to the constructor.

Upvotes: 4

Related Questions