+ 3
Constructor & Destructors
can anyone please help me out
18 Answers
+ 3
//C++ example
class Cat {
int age;
int weight;
Cat (int a, int w) {
//this is constructor
age = a ;
weight = w;
}
~Cat() {
// this is destructor;
cout << âdelete an instanceâ ;
}
}
Cat ob = new Cat(3, 25);
P.S. new Cat calls Constructor and passing 2 arguments to him like any other functions
+ 3
simply you can think of constructor &destructors like special functions (piece of code ) than runs when an object of that class is created & destoryed respectivly
+ 3
Thank you for your code.. It helpd me
+ 3
in c++ constructors and destructors have the same name as class and havenât return type, there is ~ symbol before destructor
+ 3
okay
+ 2
can you please teach me with an example for both. it will be helpful for me
+ 2
thanks buddy
+ 2
yea, i have learn class and objects in cpp but constructors and destructors are daunting me
+ 2
does constructor always has the same name as the class?
+ 2
no, it is in c++ , itâs about my c++ example.
+ 2
for example in python it calls __init__
+ 1
constructors,destructors are like special functions.
constructors get called when an object is created,
destructors get called when an object is destroyed.
+ 1
thank you Ashraf Al_Absi
+ 1
Okey
+ 1
Working :
Constructor is a special member function whose task is to initialise an object of it's class.
&
Destructor is a special member function whose task is to destroy the object created by constructor.
0
well they exist in several languages..
in js
class Obj{
constructor(){
alert("hi");}
}
man=new Obj(); //i created an object "man" from class Obj here so the constructor is called then the code alerts "hi" .
As i said they exist in several languages and i dont know if this js examole is helpful.
desteuctors are called by default in js so no need declaring them
0
I don't understand very well
- 1
if you want to understand constructors and destructors you might need to learn classes and objects first