Thread: How to declare const data member in class

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    225

    How to declare const data member in class

    Hello,
    why is the below declaration not working and what to do to make it a valid one?

    Code:
    class shape
    {
     const int p;
    
     public:
      shape()
      {
       p=10;
      }
      void display()
      {
    	cout<<p;
      }
    };

  2. #2
    Banned
    Join Date
    Nov 2007
    Posts
    678
    Code:
    class shape
    {
     const int p;
    
     public:
      shape()
      : p(10) 
      {
    //   p=10;
      }
      void display()
      {
        cout<<p;
      }
    };
    RED part was wrong!
    GREEN part is added by me, and is the right way to do this!

  3. #3
    Its hard... But im here swgh's Avatar
    Join Date
    Apr 2005
    Location
    England
    Posts
    1,688
    Just a side note, if you decalre an array size in a class, make sure you make it static.

    Code:
    class Foo
    {
    public:
       static const int ARRAY_SIZE = 10;
    };
    Double Helix STL

  4. #4
    Registered User
    Join Date
    Jul 2007
    Posts
    32
    Probabily you can do something like this:
    Code:
    Class A {
       const int _p;
    public:
         A() : _p(10) { }
         //or
         A(int size) : _p(size) {}
    };

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  3. How do i un-SHA1 hash something..
    By willc0de4food in forum C Programming
    Replies: 4
    Last Post: 09-14-2005, 05:59 AM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  5. Certain functions
    By Lurker in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2003, 01:26 AM