using c style pointer in c++ constructor

Hi

I am attempting to try out composition, so a class has an object of another class as a member.
In the case below, Glum has an object Fabulous.
I get the following error regarding the purposeful C style pointer though. Appreciate I can use string instead, but I would like to know why I get the warning message, error: incompatible types in assignment of ‘const char*’ to ‘char [20]’ for the code below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>

class Fabulous {
  private:
    char fab[20];
  public:
    Fabulous(const char * s = "C++") : fab(s) { }
    virtual void tell() { cout << fab; }
};

class Glum {
  private:
    int glib;
    Fabulous fb;

  public:
    Glum(int g = 0, const char * s = "C++");
    Glum(int g = 0, const Fabulous &);
    void tell();
};

Glum::Glum(int g = 0, const char * s) :
  glib{g}, fb{s} { }

Glum::Glum(int g = 0, Fabulous & f) :
  glib{g}, fb{f} { }

void Glum::tell() {
  fb.tell();
  std::cout << glib << "\n";
}

int main() {
  char * a = (char *)"Bjarne Stroustrup";
  Glum g1{10};
  g1.tell();
  Glum g2{10, "Hello", a};
  g1.tell();
  return 0;
}

Can anybody suggest how to solve the error?
Thanks
Last edited on
You are trying to initialize an array with a pointer.

You probably want to use the strcpy function instead.

 
std::strcpy(fab, s);

http://www.cplusplus.com/reference/cstring/strcpy/
A few other problems:
Line 8: You reference cout, but you have neither std:: nor using namespace std;

Line 18: You declare the second argument as const. However, at line 25, the second argument is non-const. Your compiler should have complained about this,

Line 18: You can't have a defaulted argument to the left of a non-defaulted argument.

Line 22,25: You don't specify default syntax on a constructor implementation.

Line 34: It's pointless (and wrong) cast a quoted literal to a non-const pointer. Most compilers store quoted literals in a read only portion of memory. If you tried to modify what the non-const pointer points to, you would get an access violation.

Line 37: You're trying to instantiate Glum with three arguments. You have no constructor that accepts three arguments.

Line 38: Did you mean: g2.tell();



Last edited on
Topic archived. No new replies allowed.