Home > Development > Removing Constness

Removing Constness


If you have a function that takes a pointer to a datatype and need to pass it a const pointer it wont work. You need to remove the constness of the variable before you pass it in.
i.e.

#include <iostream>
#include <string>

using namespace std;

void print(string* ptr){
    cout << *ptr << endl;
}

int main(int argc, char *argv[])
{

    const string name = "Blair Davidson";
    const string* nptr = &name;
    cout << *nptr << endl;
    print(const_cast<string*>(nptr));

    return 0;
}
Advertisements
Categories: Development Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: