Class Constructor with string const pointer as parameter

I know my product.cpp constructor is wrong but how can I set my private variables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//PRODUCT.h
#ifndef PROJECT1_PRODUCT_H
#define PROJECT1_PRODUCT_H

namespace Project1
{
    class Product
    {
    public:
        Product(const char *brand, const char *name, const char *size);
    private:
        char brand[25];
        char name[25];
        char size[25];
    };
#endif

}




1
2
3
4
5
6
7
8
9
10
11
12
13
// PRODUCT.cpp
#include <cstring>
using std::strcpy;

#include "Product.h"

Project1::Product::Product(const char *brand, const char *name,const char *size)
{
    // done: Implementing
    *this->brand = *brand;
    *this->name = *name;
    *this->size = *size;
}


1
2
3
4
5
6
7
//MAIN.cpp
#include "Product.h"

int main()
{
    Product p1("Coca Cola", "Coke", "12 fl oz");
}
You cannot assign char arrays like that. Each character of the data must be copied over.

This can be easily accomplished with the strcpy function:

1
2
3
strcpy( *this->brand, brand );
strcpy( *this->name, name );
strcpy( *this->size, size );


Of course... it's much easier and safer if you use actual strings instead of char arrays:

1
2
3
4
5
std::string brand;
//...


this->brand = brand;  // <- nice 'n' easy, and lots safer 


But I'm assuming you are forbidden to use strings for this assignment or something.
Or even better, use std::string and initialiser lists:

1
2
3
4
5
6
#include <string>
#include "Product.h"

Project1::Product::Product(const std::string& brnd, const std::string& nme, const std::string& sz) : brand(brnd), name(nme), size(sz)
{
}


Assuming of course you are allowed to use strings instead of raw char arrays.
Topic archived. No new replies allowed.