I'm reading 'C++ For Dummies 7th Edu' and I'v ran into this little snipet that's confusing me.

BOOK
You can add const-ness, however, as in the following

void fn(char* pName)
{
    // declare following is allowed even though
    // declared Student(const char*)
    Student s(pName);
    // ...do whatever...
}

The function fn() passes a char* string to a constructor that promises to treat the string as if it were a constant.
/BOOK
The example before this used a constructor that was almost identical Student(const* pName). The only difference I see is that the Student constructor in the fn() function doesn't have a variable name given to hold it's argument, I didn't think that was legal. I don't see what the book is driving at, all this short snippet did was to place the Student object creation in a regular function and leave out the variable name of the paramater in the student constructor? What am I missing here? Thanks.

What am I missing here?

Two things:

  1. Student s(pName) is creating a variable called s via the const char* constructor of the Student class. I get the impression you're confusing this with a function declaration given your mention of a "variable name".

  2. You can generally add a const qualifier without issue, but it cannot be removed without a cast. This is what the book is explaining. pName does not have a const qualifier, but it can be safely passed to the Student constructor that expects a const qualifier. This qualifier will be added for you automagically and the parameter to the constructor will be treated as const.

The code isn't ideal, of course. pName should be declared as const to avoid subtle issues which could arise depending on how the constructor uses the pointer.

commented: Good explanation. +13

Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.