Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!zaphod.mps.ohio-state.edu!pacific.mps.ohio-state.edu!linac!att!ucbvax!pasteur!galileo.berkeley.edu!jbuck From: jbuck@galileo.berkeley.edu (Joe Buck) Newsgroups: comp.lang.c++ Subject: Re: char *const assignment in constructor Message-ID: <11485@pasteur.Berkeley.EDU> Date: 27 Feb 91 06:31:17 GMT References: <1991Feb26.195200.8763@urbana.mcd.mot.com> Sender: news@pasteur.Berkeley.EDU Reply-To: jbuck@galileo.berkeley.edu.UUCP (Joe Buck) Organization: U.C. Berkeley -- ERL Lines: 33 In article <1991Feb26.195200.8763@urbana.mcd.mot.com> qbarnes@urbana.mcd.mot.com (Quentin Barnes) writes: >I would like to have a variable of type "char *const" (pointer itself >is const, not what it points to.) However, I would like to delay its >initialization until the contructor is called for its class. Once it >is initialized there, I would like the variable treated as const. > >Is there any way to do this in C++? Yes. class Quentin { private: char *const constPtr; public: Quentin (char *arg) : constPtr(arg) {} }; This is one of the two cases where you must use the "colon" notation to initialize members; the other is for reference members. That is, writing the constructor Quentin (char *arg) { constPtr = arg; } is illegal. Why? Because the language designers tried to make a distinction between initialization and assignment -- you can initialize a const object or a reference but you cannot assign to it. -- -- Joe Buck jbuck@galileo.berkeley.edu {uunet,ucbvax}!galileo.berkeley.edu!jbuck