How can I forbid a simple assignment MyClass=int?

  • A+

if I have a class with attributes like this:

struct MyClass {    double **arowofpointers;    int capacity; }; 

Now, if the task says "make sure this line of code in the main function is legal:

MyClass a(10); //makes a variable whose type is MyClass that has the capacity of 10 

But make sure that the following line of code in the main function is not legal:

MyClass a=10; 

Still, the following line of your code in the main function should be legal:


where, a,b and c are all variables whose type is MyClass.

Which constructors should I make? Is there anything I should set on delete or something?


Constructing an instance of type MyClass like this

MyClass a(10); 

requires a constructor that takes an integer parameter:

class MyClass {   public:     MyClass(int param);    // ... }; 

But as constructors are implicit by default (which is unfortunate), allowing for MyClass a = 10;, you need to make it explicit:

// This constructor must be called explicitly via MyClass(int) explicit MyClass(int param); 

This will make the compiler complain when it encounters MyClass a = 10;.

For the operator part of your question, you might want to have a look at this (the "Arithmetic Operators" part).


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: