www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Newbie question

reply Dune <not.yet yahoo.com> writes:
Hi,
trying to get D into my brain but somehow I'm not in sync yet...

This works (from the docs):

struct Foo {
  public:
  int data() { return m_data; }                  // read property
  int data(int value) { return m_data = value; } // write property

  private:
  int m_data;
}

void main() {
  Foo f;
  f.data = 3; // same as f.data(3);
  printf ("%d", f.data + 3); // same as return f.data() + 3;
}

This doesn't:

class Foo {
  public:
  int data() { return m_data; }                  // read property
  int data(int value) { return m_data = value; } // write property

  private:
  int m_data;
}

void main() {
  Foo f;
  f.data = 3; // same as f.data(3);
  printf ("%d", f.data + 3); // same as return f.data() + 3;
}

Thanks for any help

Dune

BTW: Maybe I will bother you guys/gals even more... depending on my grasping
skills ;)
Nov 28 2006
next sibling parent reply Stewart Gordon <smjg_1998 yahoo.com> writes:
Dune wrote:
<snip>
 This doesn't:
 
 class Foo {
   public:
   int data() { return m_data; }                  // read property
   int data(int value) { return m_data = value; } // write property
 
   private:
   int m_data;
 }
 
 void main() {
   Foo f;
   f.data = 3; // same as f.data(3);
<snip> Welcome to D. Classes in D have reference semantics. That is, by declaring a Foo, you are declaring not an object, but a reference to one. Initially, any reference is null, i.e. it doesn't refer to anything. Before you can do anything with it, you must make it refer to an object. f = new Foo; This creates a new object of type Foo, and makes f refer to it. Once that's done, then you can do stuff with it. Stewart. -- -----BEGIN GEEK CODE BLOCK----- Version: 3.1 GCS/M d- s:- C++ a->--- UB P+ L E W++ N+++ o K- w++ O? M V? PS- PE- Y? PGP- t- 5? X? R b DI? D G e++++ h-- r-- !y ------END GEEK CODE BLOCK------ My e-mail is valid but not my primary mailbox. Please keep replies on the 'group where everyone may benefit.
Nov 28 2006
parent Dune <not.yet yahoo.com> writes:
Duh!

While reading your post it was obvious that I forgot the essential stuff.
Thanks.

Dune
Nov 28 2006
prev sibling parent David L. Davis <SpottedTiger yahoo.com> writes:
Hi Dune,


    You needed the following line change "Foo f = new Foo;" since
a class is an object, you needed to create it first before you
using it.

class Foo {
  public:
  int data() { return m_data; }                  // read property
  int data(int value) { return m_data = value; } // write property

  private:
  int m_data;
}

void main() {
  Foo f = new Foo;
  f.data = 3; // same as f.data(3);
  printf ("%d", f.data + 3); // same as return f.data() + 3;
}

David L
Nov 28 2006