首页 > 其他分享 >class

class

时间:2023-01-10 19:34:15浏览次数:38  
标签:cout int Geeks constructors Destructor class

1. Constructor

  1. Default constructors
  2. Parameterized constructors
  3. Copy constructors
// C++ program to demonstrate constructors

#include <bits/stdc++.h>
using namespace std;
class Geeks
{
	public:
	int id;
	
	//Default Constructor
	Geeks()
	{
		cout << "Default Constructor called" << endl;
		id=-1;
	}
	
	//Parameterized Constructor
	Geeks(int x)
	{
		cout <<"Parameterized Constructor called "<< endl;
		id=x;
	}
};
int main() {
	
	// 1. obj1 will call Default Constructor
	Geeks obj1;
	cout <<"Geek id is: "<<obj1.id << endl;
	
	// 2. obj2 will call Parameterized Constructor
	Geeks obj2(21);
	cout <<"Geek id is: " <<obj2.id << endl;

	// 3. A Copy Constructor creates a new object, which is exact copy of the existing object. The compiler provides a default Copy Constructor to all the classes. 
	// Syntax: class-name (class-name &){}
	return 0;
}

2. Destructors

Destructor is another special member function that is called by the compiler when the scope of the object ends.

// C++ program to explain destructors

#include <bits/stdc++.h>
using namespace std;
class Geeks
{
	public:
	int id;
	
	//Definition for Destructor
	~Geeks()
	{
		cout << "Destructor called for id: " << id <<endl;
	}
};

int main()
{
	Geeks obj1;
	obj1.id=7;
	int i = 0;
  	while ( i < 5 )
	{
		Geeks obj2;
		obj2.id=i;
		i++;	
	} // Scope for obj2 ends here

	return 0;
} // Scope for obj1 ends here

标签:cout,int,Geeks,constructors,Destructor,class
From: https://www.cnblogs.com/shendaw/p/17041209.html

相关文章