Microsoft KB Archive/117794

= PRB: Compiler Errors when Implementing CObject-Derived Class =

Article ID: 117794

Article Last Modified on 11/21/2006

-

APPLIES TO

 Microsoft Foundation Class Library 4.2, when used with:  Microsoft C/C++ Professional Development System 7.0

 Microsoft Visual C++ 1.0 Professional Edition

 Microsoft Visual C++ 1.5 Professional Edition

 Microsoft Visual C++ 1.51</li></ul>

 Microsoft Visual C++ 1.52 Professional Edition</li></ul>

 Microsoft Visual C++ 5.0 Learning Edition</li></ul>

 Microsoft Visual C++ 2.0 Professional Edition</li></ul>

 Microsoft Visual C++ 4.0 Professional Edition</li></ul> </li></ul>

-

<div class="notice_section">

This article was previously published under Q117794

<div class="symptoms_section">

SYMPTOMS
When you implement a class derived from CObject and your code is written so that the copy constructor or assignment operator for the class needs to be called, the compiler may report errors similar to the following:

error C2660: 'CSample::CSample' : function does not take 1 parameters

error C2582: 'CSample' : 'operator =' function is unavailable

You can reproduce the problem by compiling the sample code in the "RESOLUTION" section, below.

NOTE: Using Visual C++, 32-bit Edition, versions 2.x and 4.0, the sample code shown in this article generates the following error messages:

error C2558: 'CSample::CSample' : no copy constructor available

error C2582: 'CSample' : 'operator =' function is unavailable

<div class="cause_section">

CAUSE
The reason for the compiler errors is that CObject declares a private copy constructor and assignment operator in the AFX.H file. The compiler does not generate a default copy constructor and assignment operator for the CObject-derived class because of this. Because the compiler does not find these functions declared in the class, it reports the errors.

<div class="resolution_section">

RESOLUTION
To avoid the compiler errors, you need to implement a copy constructor and assignment operator for the CObject-derived class. This is illustrated in the sample code below. You can avoid the errors by uncommenting the lines indicated in the sample code.

Sample Code
/* Compile options needed: /c

// replace with #define _CONSOLE when compiling for Windows NT  #define _DOS

#include <afx.h>

class CSample : public CObject {  private: short m_nValue; public: // uncomment the lines below to avoid the compiler errors //   CSample {} //   CSample( const CSample &s )  // copy ctor //       { m_nValue = s.m_nValue; } //   CSample& operator=( const CSample &s )  // assignment operator //       { m_nValue = s.m_nValue; return *this; } };

void main {      CSample a;       CSample b = a;       a = b;   }

<div class="references_section">