How to declare const data member in class

This is a discussion on How to declare const data member in class within the C++ Programming forums, part of the General Programming Boards category; Hello, why is the below declaration not working and what to do to make it a valid one? Code: 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,479
    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;
    };
    I'm just trying to be a better person - My Name Is Earl

  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, 03: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, 12:26 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21