← Back to C++ Course | Chapter 17: Advanced C++ | Lesson 9 of 17

C++ का dynamic_cast

dynamic_cast program चलते हुए safely एक parent pointer को एक child pointer में बदलता है, और बताता है अगर यह actually वह child न हो। यह box खोलने से पहले एक label check करने जैसा है।
Syntax
cpp
Derived *pointer_name = dynamic_cast<Derived*>(base_pointer);  // nullptr if it fails

Derived &reference_name = dynamic_cast<Derived&>(base_reference);  // throws if it fails

dynamic_cast क्या है?

dynamic_cast operator polymorphic class hierarchies में safe downcasting के लिए इस्तेमाल होता है। यह runtime पर check करता है कि एक base class pointer actually एक specific derived class object की ओर point करता है या नहीं।

उदाहरण: What is dynamic_cast?

cpp
// Include std::cout and std::cin
#include <iostream>

// Define the type Animal
class Animal {
// Members below can be accessed from outside the class
public:
	virtual ~Animal() {}
};

// Define the type Dog
class Dog : public Animal {};

// Program execution starts in main()
int main() {
	// Allocate an object on the heap with new
	Animal *a = new Dog();
	Dog *d = dynamic_cast<Dog *>(a);
	// Print to the console with cout
	std::cout << (d != nullptr) << std::endl;
	// Free the heap memory with delete
	delete a;
	return 0;
}

References के साथ Casting

आप dynamic_cast references के साथ भी इस्तेमाल कर सकते हैं। क्योंकि null reference जैसी कोई चीज़ नहीं होती, अगर conversion fail हो तो dynamic_cast एक 'std::bad_cast' exception throw करता है।

उदाहरण: Casting with References

cpp
// Include std::cout and std::cin
#include <iostream>

// Define the type Animal
class Animal {
// Members below can be accessed from outside the class
public:
	virtual ~Animal() {}
};

// Define the type Dog
class Dog : public Animal {};

// Program execution starts in main()
int main() {
	Dog realDog;
	Animal &a = realDog;
	// Try code that might throw an exception
	try {
		Dog &d = dynamic_cast<Dog &>(a);
		// Print to the console with cout
		std::cout << "Cast succeeded" << std::endl;
	// Handle the exception if one was thrown
	} catch (std::bad_cast &e) {
		std::cout << "Cast failed" << std::endl;
	}
	return 0;
}

Polymorphism की Requirement

dynamic_cast के काम करने के लिए, base class polymorphic होना चाहिए। इसका मतलब है base class को कम से कम एक virtual function declare करना चाहिए, जैसे एक virtual destructor।

उदाहरण: Requirement of Polymorphism

cpp
// Include std::cout and std::cin
#include <iostream>

// Define the type Animal
class Animal {
// Members below can be accessed from outside the class
public:
	virtual ~Animal() {}
};

// Define the type Dog
class Dog : public Animal {};

// Program execution starts in main()
int main() {
	// Allocate an object on the heap with new
	Animal *a = new Dog();
	Dog *d = dynamic_cast<Dog *>(a);
	// Print to the console with cout
	std::cout << (d != nullptr) << std::endl;
	// Free the heap memory with delete
	delete a;
	return 0;
}

Upcasting बनाम Downcasting

Upcasting एक derived pointer को एक base pointer में convert करता है और compiler से implicitly handle होता है। Downcasting एक base pointer को एक derived pointer में convert करता है और runtime checks perform करने के लिए एक explicit dynamic_cast चाहिए।

उदाहरण: Upcasting vs Downcasting

cpp
// Include std::cout and std::cin
#include <iostream>

// Define the type Animal
class Animal {
// Members below can be accessed from outside the class
public:
	virtual ~Animal() {}
};

// Define the type Dog
class Dog : public Animal {};

// Program execution starts in main()
int main() {
	Dog d;
	Animal *a = &d;
	Dog *back = dynamic_cast<Dog *>(a);
	// Print to the console with cout
	std::cout << (back != nullptr) << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

Downcasting Best Practices

हमेशा check करें कि एक dynamic_cast से returned pointer इस्तेमाल करने से पहले nullptr है या नहीं। यह आपके program को crash होने से रोकता है अगर cast runtime पर fail हो जाए।

उदाहरण: Downcasting Best Practices

cpp
// Include std::cout and std::cin
#include <iostream>

// Define the type Animal
class Animal {
// Members below can be accessed from outside the class
public:
	virtual ~Animal() {}
};

// Define the type Dog
class Dog : public Animal {};
class Cat : public Animal {};

// Program execution starts in main()
int main() {
	// Allocate an object on the heap with new
	Animal *a = new Cat();
	Dog *d = dynamic_cast<Dog *>(a);
	// Check whether d == nullptr
	if (d == nullptr) {
		// Print to the console with cout
		std::cout << "Not actually a Dog" << std::endl;
	}
	delete a;
	return 0;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. बिना virtual functions वाली एक class पर dynamic_cast इस्तेमाल करना।
  2. एक failed pointer cast के बाद nullptr check न करना।
  3. यह भूल जाना कि एक failed reference cast std::bad_cast throw करता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.