Thread: incompatible types in assignment of 'char*'

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    103

    incompatible types in assignment of 'char*'

    I am trying to compile program given in link C++/Classes and Inheritance - Wikiversity but it gives error

    Code:
    #include<iostream>
    
    class Dog
    {
    private:
        char name[25];
        int gender;
        int age;
        int size;
        bool healthy;
    
    
    public:
        char* getName()   { return name;   }
        int   getGender() { return gender; }
        int   getAge()    { return age; }
        int   getSize()   { return size; }
        bool  isHealthy() { return healthy; }
        void  setHealthy(bool dhealthy) { healthy = dhealthy; }
        void  setName(char* dname)      { name = dname; }
    };
    
    
    int main()
    {
        Dog lucy;
    
    
        std::cout << "lucy's name   is " << lucy.getName()   << std::endl;
        std::cout << "lucy's gender is " << lucy.getGender() << std::endl;
        std::cout << "lucy's age    is " << lucy.getAge()    << std::endl;
        std::cout << "lucy's size   is " << lucy.getSize()   << std::endl;
        if(lucy.isHealthy())
            std::cout << "lucy is healthy"       << std::endl;
        else
            std::cout << "lucy isn't healthy :(" << std::endl;
    
    
        std::cout << "Now I'm changing lucy abit..." << std::endl;
    
    
        lucy.setHealthy(!(lucy.isHealthy()));
        lucy.setName("lUCY");
    
    
        std::cout << "lucy's name   is " << lucy.getName()   << std::endl;
        std::cout << "lucy's gender is " << lucy.getGender() << std::endl;
        std::cout << "lucy's age    is " << lucy.getAge()    << std::endl;
        std::cout << "lucy's size   is " << lucy.getSize()   << std::endl;
        if(lucy.isHealthy())
            std::cout << "lucy is healthy"       << std::endl;
        else
            std::cout << "lucy isn't healthy :(" << std::endl;
    
    
        return 0;
    }
    In member function 'void Dog::setName(char*)':
    error: incompatible types in assignment of 'char*' to 'char [25]'
    void setName(char* dname) { name = dname; }
    ^~~~~
    In function 'int main()':
    warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
    lucy.setName("lUCY");
    ^
    Last edited by abhi143; 2 Weeks Ago at 07:18 AM.

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,456
    You should really consider using std::string instead of the error prone C-strings.

    In your setName() function you should first verify that the passed C-string is small enough to fit into the name array, then use strcpy() to copy the passed string into the name array.

    Also do your realize that you're trying to print your uninitialized class variables on lines 29 thru 36?

    All of your getXXXX() member functions should be const qualified.
    Code:
    ...
        int   getGender() { return gender; } const
    ...
    Lastly, for now, you really should find a different source. The one you've found seems to have quite a few deficiencies and is really doing you a disservice.

    Edit: I wonder why gender is an int instead of either a string or a single char.

  3. #3
    Registered User
    Join Date
    Aug 2019
    Location
    Inside a Singularity
    Posts
    177
    Lastly, for now, you really should find a different source. The one you've found seems to have quite a few deficiencies and is really doing you a disservice.
    Not really, Wikiversity is a really good source to learn from. @abhi143 rewrote the code in a different way, probably for practice, and that's what has produced him his errors. You can see the website for yourself, it's pretty good for someone starting out on classes and inheritance and abstraction.

    Also do your realize that you're trying to print your uninitialized class variables on lines 29 thru 36?
    Wikiversity: However, if we run this program, we might have a little problem. We have never initialized lucy's properties...

    Well, they try and teach about initialization through this. You probably didn't look through the website but that's not your fault. It's a really reliable place to learn from.

    Code:
    In member function 'void Dog::setName(char*)':
    Code:
    error: incompatible types in assignment of 'char*' to 'char [25]'
    void setName(char* dname) { name = dname; }
    ^~~~~
    In function 'int main()':
    warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
    lucy.setName("lUCY");
    ^
    



    You can't set one pointer to another pointer... Use std::string as mentioned (and written) on the website instead of experimenting with C-style strings if you're wanting to learn C++. Or, if you're trying to convert the C++ code to C code, you should do what @jimblumberg suggested.

  4. #4
    Registered User
    Join Date
    May 2017
    Posts
    103
    Quote Originally Posted by jimblumberg View Post
    You should really consider using std::string instead of the error prone C-strings..

    Code:
    #include<iostream>using namespace std;
     
    class Dog
    {
    private:
        char name[25];
        int gender;
        int age;
        int weight;
        
    public:
        char* getName()   { return name;   }
        int   getGender() { return gender; }
        int   getAge()    { return age; }
        int   getWeight() { return weight; }
          
    };
     
    int main()
    {
        Dog lucy;
     
        cout << "lucy's name   is " << lucy.getName()   << endl;
        cout << "lucy's gender is " << lucy.getGender() << endl;
        cout << "lucy's age    is " << lucy.getAge()    << endl;
        cout << "lucy's Weight is " << lucy.getWeight()   << endl;
        
        return 0;
    }
    lucy's name is a
    lucy's gender is 4201152
    lucy's age is 6422368
    lucy's Weight is 4201243

    How to print correct details of lucy's ?

  5. #5
    Registered User
    Join Date
    Aug 2019
    Location
    Inside a Singularity
    Posts
    177
    > How to print details of lucy's ?

    Exactly the way you do. Again consider using std::string as that's what you should be doing if you want to learn C++. Read a little further in the Wikiversity Guide you're referring to. It does teach you about Constructors and Initialization. Right now, all the details you print are just the stuff existing in uninitialized memory, exactly what @jimblumberg mentioned. You need to complete a topic completely in order to get the simplest program of that topic to work. Learning in bits and pieces won't do you good. Good luck

  6. #6
    Registered User
    Join Date
    May 2017
    Posts
    103
    Quote Originally Posted by Zeus_ View Post
    > How to print details of lucy's ?

    Exactly the way you do. Again consider using std::string as that's what you should be doing if you want to learn C++. Read a little further in the Wikiversity Guide you're referring to. It does teach you about Constructors and Initialization. Right now, all the details you print are just the stuff existing in uninitialized memory, exactly what @jimblumberg mentioned. You need to complete a topic completely in order to get the simplest program of that topic to work. Learning in bits and pieces won't do you good. Good luck
    There is no much information given in link. I created program after spending few time

    Code:
    #include<iostream>
    using namespace std;
      
    class Dog
    {
    private:
    
    
        int age;
    	char gender;
        float weight;
         
    public:
      
        int getAge()    
    	{
    		cout << "\nEnter lucy's age: ";
    		 cin >> age;
    		return age; 		
    	}
    	
    	char getGender() 
    	
    	{ 
            cout << "\nEnter lucy's Gender: ";
    		 cin >> gender;	
    	    return gender;
    	}
    	
    	float  getWeight()
    	{ 
    	    cout << "\nEnter lucy's Weight: ";
    		cin >> weight;
    		
    		return weight;
    	}
           
    };
      
    int main()
    {
        Dog lucy;
      
        cout << "lucy's age is " << lucy.getAge()    << endl;
    	cout << "lucy's gender is " << lucy.getGender() << endl;
    	cout << "lucy's Weight is " << lucy.getWeight()   << endl;
    
    
        return 0;
    }
    Enter lucy's age: 5
    lucy's age is 5


    Enter lucy's Gender: m
    lucy's gender is m


    Enter lucy's Weight: 20
    lucy's Weight is 20

  7. #7
    Registered User
    Join Date
    Aug 2019
    Location
    Inside a Singularity
    Posts
    177
    > There is no much information given in link.

    There's enough information on there than you've attempted to read. I've looked through myself and everything about initialising properties is present. Look carefully! Read the part under constructors. It may be slightly advanced to you, I feel, and so consider finding a book/guide/online tutorial that explains you classes from the basics. Default Constructors and how writing your own constructor disables the one provided by the compiler, etc etc etc. Additionally you'd also have to learn more on Polymorphism (...
    Overloading) to get a grasp of the concepts used in most beginner-ish tutorials.

    Code:
    class Dog[edit]
    
    Structs are containers whose properties are always public. In order to gain control over what is public and what isn't, we will have to use a class. Let us see how the Dog class would look like in a class instead of a struct:
    #include <string>
    
    class Dog
    {
    private:
        std::string name;
        int gender;
        int age;
        int size;
        bool healthy;
    };
    
    Now our dogs precious properties aren't public for everyone to view and change. However, this raises a little problem. We can't change them either. Only other dogs can see and change them. In order to be able to access a Dog's private properties, we would have to make a function to do so. This brings us to our next chapter.
    Dogs with Methods[edit]
    
    Classes can have functions in them. These functions are called methods. Methods can access all, and even private, properties and methods (yes, methods can be private) of its class. Let us make some methods to get our dog's information...
    #include <string>
    
    class Dog
    {
    private:
        std::string name;
        char gender;
        int age;
        int size;
        bool healthy;
    
    public:
        std::string getName()  const { return name;   } 
        int   getGender() const { return gender; }
        int   getAge()  const  { return age; }
        int   getSize()  const  { return size; }
        bool  isHealthy() const { return healthy; }
        void  setHealthy(bool dhealthy) { healthy = dhealthy; }
        void  setName(const std::string& dname)      { name = dname; }
    };
    
    #include <iostream>
    
    int main()
    {
        Dog lucy;
    
        std::cout << "lucy's name   is " << lucy.getName()   << std::endl;
        std::cout << "lucy's gender is " << lucy.getGender() << std::endl;
        std::cout << "lucy's age    is " << lucy.getAge()    << std::endl;
        std::cout << "lucy's size   is " << lucy.getSize()   << std::endl;
        if(lucy.isHealthy())
            std::cout << "lucy is healthy"       << std::endl;
        else
            std::cout << "lucy isn't healthy :(" << std::endl;
    
        std::cout << "Now I'm changing lucy abit..." << std::endl;
    
        lucy.setHealthy(!(lucy.isHealthy()));
        lucy.setName("lUCY");
    
        std::cout << "lucy's name   is " << lucy.getName()   << std::endl;
        std::cout << "lucy's gender is " << lucy.getGender() << std::endl;
        std::cout << "lucy's age    is " << lucy.getAge()    << std::endl;
        std::cout << "lucy's size   is " << lucy.getSize()   << std::endl;
        if(lucy.isHealthy())
            std::cout << "lucy is healthy"       << std::endl;
        else
            std::cout << "lucy isn't healthy :(" << std::endl;
    
        return 0;
    }
    
    However, if we run this program, we might have a little problem. We have never initialized lucy's properties...
    Constructors[edit]
    
    In order to initialize lucy's properties, we could write a method that would do it for us, and call it every time we make a dog. However, C++ already provides us such a method. A constructor is a method which is called every time a new object is created. To use this nice little thing provided to us by C++, we will have to write a method which returns no value, and has the same name as the class. Here's Dog written using a constructor:
    #include <string>
    
    class Dog
    {
    private:
        std::string name;
        char gender;
        int age;
        int size;
        bool healthy;
    
    public:
        std::string getName() const  { return name;   }
        char   getGender() const { return gender; }
        int   getAge() const   { return age; }
        int   getSize() const   { return size; }
        bool  isHealthy() { return healthy; }
        void  setHealthy(bool dhealthy) { healthy = dhealthy; }
        void  setName(const std::string& dname)      { name = dname; }
    
        Dog() :
            name("Lucy"), gender('f'), age(3), size(4), healthy(true)
        {}
    };
    
    From now on, every dog we instantiate will have the name "Lucy", be of gender 1, aged 3, sized 4 and healthy. Well, what if you want some diversity? No problem. Constructors with parameters!
        Dog(const std::string& dname, int dgender, int dage, int dsize, bool dhealthy) :
            name(dname), gender(dgender), age(dage), size(dsize), healthy(dhealthy)
        {}
    
    If you have both constructors in your Dog class, you can now either create a dog as always, which will have the default values (named "Lucy" etc etc), or you could use RAII to make your customized dog as follows:
    #include <iostream>
    
    int main()
    {
        Dog scruffy("Scruffy", 'm', 8, 6, false);
        
        std::cout << "scruffy's name   is " << scruffy.getName()   << std::endl;
        std::cout << "scruffy's gender is " << scruffy.getGender() << std::endl;
        std::cout << "scruffy's age    is " << scruffy.getAge()    << std::endl;
        std::cout << "scruffy's size   is " << scruffy.getSize()   << std::endl;
        if(scruffy.isHealthy())
            std::cout << "scruffy is healthy"       << std::endl;
        else
            std::cout << "scruffy isn't healthy :(" << std::endl;
    
        return 0;
    }
    
    Last edited by Zeus_; 2 Weeks Ago at 02:52 AM.

  8. #8
    Registered User
    Join Date
    May 2017
    Posts
    103
    Quote Originally Posted by Zeus_ View Post
    > There's enough information on there than you've attempted to read.
    I agree with you I have to spent some time on reading that's what I am doing

    Do you have any advice on my previous code. I wrote it myself so may be somewhere I am wrong

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,248
    You should not have the member functions do interactive I/O like that.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    Registered User
    Join Date
    May 2017
    Posts
    103
    Quote Originally Posted by laserlight View Post
    You should not have the member functions do interactive I/O like that.
    if possible Can you give any hint How it should be ?

  11. #11
    Registered User
    Join Date
    Aug 2019
    Location
    Inside a Singularity
    Posts
    177
    In general, your Class Methods shouldn't be doing interactive I/O. By interactive, @laserlight means you shouldn't be having things like "Enter Lucy's age: " in your method that does I/O. It takes a lot to take understand the "why" because you are indeed learning one of the hardest languages out there for beginners. You'll gradually understand with time the "why" when you start reading about data abstraction etc. For now, you needn't worry about it and should just care about getting things to work and be able to understand them.
    Make your I/O methods un-interactive. Do the interaction handling separately. Also, you'd probably want the Dog class for different dogs too and not just Lucy. The tutorial explains very well on how to do just that. Also, if seeing things like const written everywhere makes it confusing, you can probably ignore that for now. It's just present so that your methods are valid for const objects too.

    Your code should be more like:

    Code:
    void SetAge ()
    {
          cin >> Age; // You actually need to check here if the user entered a number and not characters but don't worry about that for now
    }
    
    int GetAge () const
    {
         return Age;
    }
    And your interaction should be more like:

    Code:
         cout << "Enter " << dog.GetName () << " 's age: "; dog.SetAge ();
         // Assuming "dog" is an instance/object of your Dog class and GetName has been properly defined the way it should be and assuming the name of the dog has been entered already before filling in the age
    Last edited by Zeus_; 2 Weeks Ago at 11:29 AM.

  12. #12
    Registered User
    Join Date
    May 2017
    Posts
    103
    Quote Originally Posted by Zeus_ View Post
    In general, your Class Methods shouldn't be doing interactive I/O. By interactive, @laserlight means you shouldn't be having things like "Enter Lucy's age: " in your method that does I/O. It takes a lot to take understand the "why" because you are indeed learning one of the hardest languages out there for beginners. You'll gradually understand with time the "why" when you start reading about data abstraction etc. For now, you needn't worry about it and should just care about getting things to work and be able to understand them.
    yes Practice will make me perfect. I don't get age in method

    How does it looks
    Code:
    #include<iostream>using namespace std;
       
    class Dog{
       private: 
         int age;
       
       public:
         void setAge (int A) {   // Set Age
    		 age = A;
    	 }
    	
         int getAge() {      // Get Age 
           return age;         
         }
     };
       
    int main(){
        Dog lucy;  
    	lucy.setAge(5);	
    	cout << "lucy's age is " << lucy.getAge() <<endl;
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 06-01-2015, 07:13 AM
  2. incompatible types in assignment
    By tetartos in forum C Programming
    Replies: 9
    Last Post: 11-27-2011, 09:39 AM
  3. incompatible types in assignment
    By Adam Rinkleff in forum C Programming
    Replies: 2
    Last Post: 07-13-2011, 01:10 AM
  4. Incompatible types in assignment.
    By killpoppop in forum C Programming
    Replies: 36
    Last Post: 12-22-2008, 12:08 PM
  5. incompatible types in assignment
    By vapanchamukhi in forum C Programming
    Replies: 6
    Last Post: 09-19-2008, 07:45 AM

Tags for this Thread