hi everyone,

i have a constructor like this,

CStack(int n)
	{
		bottom_ = new char[n];
		top_ = bottom_;
		size_ = n;
	}

In my main class i call the constructor by creating a

CStack(5); // bottom_ =  new char [5];

my question is can increment the size of the stack by using a copy constructor?

Dani AI

Generated

Short answer: a copy constructor does not increase the capacity of an existing object — it builds a new object from an existing one. asked whether a copy constructor can be used to "increment the size" of the stack; correctly noted that a copy ctor copies. You can make the copy have a larger internal buffer, but doing so changes expected semantics and is confusing; a resize operation should be explicit.

Implement a proper deep-copy copy constructor plus matching destructor and assignment to avoid shallow-pointer bugs (the Rule of Three). Example pattern (illustrative) shows how the new object allocates its own buffer and copies only the used elements so the copy is independent:

CStack(const CStack& other)
  : capacity_(other.capacity_), data_(new char[other.capacity_])
{
  std::size_t used = other.top_ - other.data_;
  std::copy(other.data_, other.data_ + used, data_);
  top_ = data_ + used;
}

Make resizing a separate member. A safe resize does: allocate new buffer, copy used elements, delete old buffer, update pointers and capacity. Prefer the copy-and-swap idiom for assignment to provide strong exception safety.

If managing raw memory is the source of confusion, switch to a standard container (for example, std::vector<char>) and let it handle allocation and resizing. That reduces bugs and gives portable, well-documented behavior.

Further reading: the copy-constructor rules and behavior are documented on cppreference copy constructor, and std::vector explains automatic resizing and capacity strategies std::vector.

Cautions: always keep the top/index relative to the buffer when copying or resizing; implement destructor/operator= to avoid double-delete; avoid surprising behavior (a copy that silently grows capacity).

I think a copy constructor as it name suggests creates a copy of the class-variable that is passed to it as a parameter/argument.

Unless the variable being passed has incremented the value.. I'm pretty unsure about it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.