Pointers in C++

Its About pointers.

Page 1 of 1

2 Replies - 1444 Views - Last Post: 08 April 2006 - 09:34 AM Rate Topic: -----

#1 jignesh145  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 08-April 06

Pointers in C++

Posted 08 April 2006 - 07:50 AM

#include<iostream.h>
#include<conio.h>

struct link
  {
    int data;
    link* next;
  };

class linklist
  {
    private:
      link* first;

    public:
      linklist()
        {
          first = NULL;
        }
      void addItem(int d);
      void display();
   };

void linklist::addItem(int d)
  {
    link* newlink = new link;
    newlink->data = d;
  newlink->next = first;
    first = newlink;
  }
void linklist::display()
  {
    int temp = 0;
    link* current = first;
    while(current != NULL)
      {
        cout<< endl<<"The Data at node: " << temp << " " <<current->data<<endl;
        current = current->next;
        temp++;
      }
    }

void main()
  {
     linklist l1;   // why not - linklist l1 = new linklist();
     l1.addItem(12);
     l1.addItem(14);
     l1.addItem(15);
     l1.addItem(20);

     l1.display();
     getch();
  }



Question:-----Why i cant create object of linklist using new operator.........linklist l1 = new linklist();

This post has been edited by Dark_Nexus: 09 April 2006 - 10:38 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Pointers in C++

#2 William_Wilson  Icon User is offline

  • lost in compilation
  • member icon

Reputation: 205
  • View blog
  • Posts: 4,807
  • Joined: 23-December 05

Re: Pointers in C++

Posted 08 April 2006 - 09:33 AM

Though i'm not sure this is the place to have asked this question, it is a simple answer.
when you use the 'new' command it allocates memory, this memory is stored on the heap, thus it is created dynamically. In C/C++ when you do this, you must create a pointer to a memory location, not just declare it (I assume you have done java or some language which allows this)
do this instead:
linklist* l1 = new linklist();



then to access parts of l1 you must use:
l1->additem(); //for example


read as l1 points to.
It is all about pointers, even in variable creation.
Was This Post Helpful? 0
  • +
  • -

#3 Mrafcho001  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 41
  • View blog
  • Posts: 769
  • Joined: 01-November 05

Re: Pointers in C++

Posted 08 April 2006 - 09:34 AM

because you are not creating a pointer you are creating an object

linkedlist* l1 = new linkedlist; // now you are creating a pointer.

Also this should go in the C++ forums, not introduction.

This post has been edited by Mrafcho001: 08 April 2006 - 09:35 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1