Tryb Ghost
Tryb Ghost

Reputation: 439

How to create a constructor which takes in a char array?

I have a class, which take in a char array of size specified by a constexpr.

Message.h:

constexpr size_t InputBufferSize = 32;

class Message
{
private:
    char input[InputBufferSize];
    int size;
public:
    //constructor
    Message(char input[], int size);
    //deconstructor
    ~Message();

    int getSize();
};

I'm confused by how to define the constructor, and then create a new instance of that class using the constructor due to the char array. Here is my try (out of a few things I tried):

Message.cpp:

#include "Message.h"

Message::Message(char input[], int size) {
    this->input[InputBufferSize] = input[];
    this->size = size;
}

Message::~Message() { }


int Message::getSize() {
    return size;
}

main.cpp:

#include <iostream>
#include "Message.h"

int main()
{
    char charinp; 
    char input[InputBufferSize] = { 'a','b','c','d','e','f' };

    Message ms1(input[], 1);

    std::cout << ms1.getSize() << std::endl;

    std::cin >> charinp;

    return 0;
}

I'd like to create a constructor with an array as on of its parameters, where the array already has a set size, and then create an object from that. The array to be passed into the object will always be of the same size, which is the size of the array the constructor is set to take in.

Upvotes: 0

Views: 3009

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596287

Message(char input[], int size);

The use of [] in a parameter declaration is just syntax sugar, the compiler will interpret char input[] as char* input instead.

this->input[InputBufferSize] = input[];

This is not legal code. You need to use (std::)memcpy() or std::copy()/std::copy_n() to copy an array to another array:

memcpy(this->input, input, size);

std::copy(input, input + size, this->input);

std::copy_n(input, size, this->input);

On a side note, you should make sure that size does not exceed InputBufferSize before copying the input array:

size = std::min(size, InputBufferSize);
Message ms1(input[], 6);

This is also not legal code. You need to drop the [] when passing the array to a parameter:

Message ms1(input, 6);
std::cin >> charinp;

On a side note, you can use std::cin.get() instead, and remove charinp from your code (since you don't use it anyway).

Upvotes: 1

abdulwasey20
abdulwasey20

Reputation: 837

You are using Message ms1(input[], 6); in your main function,try changing it to Message ms1(input, 6);. The reason for this is that you have already declared the array char input[] and you have to refer it as inputafter you have declared it not input[].

Upvotes: 1

Related Questions